rails has_many:通过has_many:through

blo*_*ilk 11 ruby orm ruby-on-rails associations rails-activerecord

我想知道我可以在多大程度上使用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
Run Code Online (Sandbox Code Playgroud)

我可以设置这些漂亮的快捷方式User.businesses,Provider.bids但是做些什么User.bids呢?是否可以关联一个协会,可以这么说?

EmF*_*mFi 5

这是完全可能的,但需要一些额外的工作.以下模型定义与nested_has_many插件结合使用,您只需获取属于用户的所有出价@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
Run Code Online (Sandbox Code Playgroud)

但是,从出价中获取用户将需要更多工作.

  • 这是可能的,但需要注意你的嵌套深度,因为你可以陷入数据库和rails应用程序.话虽这么说,我写了一篇博文,详细介绍了如何使用nested_has_many_through来做到这一点:http://kconrails.com/2010/01/28/nesting-has_many-through-relationships-in-ruby-on-rails/ (2认同)