A company has many locations (Location has company_id column). A location has many items and an item has many locations (join table).
company.rb
has_many :locations
location.rb
belongs_to :company
has_many :items, through: :item_locations
has_many :item_locations, :dependent => :destroy
item.rb
has_many :item_locations, :dependent => :destroy
has_many :locations, through: :item_locations
item_location.rb
belongs_to :item
belongs_to :location
Can I retrieve all items for a company, without adding company_id to Item?
Sure, just change your Company
relationships to:
has_many :locations
has_many :item_locations, through: :locations
has_many :items, through: :item_locations
This should let you call company.items
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.