首页 > 解决方案 > Rails has_man 通过关联

问题描述

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

公司.rb

has_many :locations

位置.rb

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 添加到项目的情况下检索公司的所有项目吗?

标签: ruby-on-rails

解决方案


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

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

这应该让你打电话company.items


推荐阅读