我想知道我可以在多大程度上使用 Rails 中的关联。考虑以下因素:
class User < ActiveRecord::Base
has_one :provider
has_many :businesses, :through => :provider
end
class Provider < ActiveRecord::Base
has_many :businesses
has_many :bids, :through => :businesses
belongs_to :user
end
class Business < ActiveRecord::Base
has_many :bids
belongs_to :provider
end
class Bid < ActiveRecord::Base
belongs_to :business
end
我能够设置这些漂亮的快捷方式,例如 User.businesses
和 Provider.bids
但如何设置 User.bids
?是否可以关联一个协会,可以这么说?
最佳答案
这是完全可能的,但需要一些额外的工作。以下模型定义与 nested_has_many plugin 结合使用您只需使用 @user.bids
class User < ActiveRecord::Base
has_one :provider
has_many :businesses, :through => :provider
has_many :bids, :through => :businesses
end
class Provider < ActiveRecord::Base
has_many :businesses
has_many :bids, :through => :businesses
belongs_to :user
end
class Business < ActiveRecord::Base
has_many :bids
belongs_to :provider
end
class Bid < ActiveRecord::Base
belongs_to :business
end
然而,通过出价获得用户需要更多的工作。
关于ruby-on-rails - rails has_many :through has_many :through,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2051927/