繁体   English   中英

Rails has_many 通过关联

[英]Rails has_many through association

一家公司有很多位置(位置有 company_id 列)。 一个位置有很多项目,一个项目有很多位置(连接表)。

公司.rb

has_many :locations

位置文件

belongs_to :company
has_many :items, through: :item_locations
has_many :item_locations, :dependent => :destroy

项目.rb

has_many :item_locations, :dependent => :destroy
has_many :locations, through: :item_locations

item_location.rb

belongs_to :item
belongs_to :location

我可以检索公司的所有项目,而不将 company_id 添加到项目吗?

当然,只需将您的Company关系更改为:

has_many :locations
has_many :item_locations, through: :locations
has_many :items, through: :item_locations

这应该让你打电话company.items

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM