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
呢?是否可以关联一个协会,可以这么说?
这是完全可能的,但需要一些额外的工作.以下模型定义与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)
但是,从出价中获取用户将需要更多工作.