ruby-on-rails - 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 添加到项目的情况下检索公司的所有项目吗?
解决方案
当然,只需将您的Company
关系更改为:
has_many :locations
has_many :item_locations, through: :locations
has_many :items, through: :item_locations
这应该让你打电话company.items
推荐阅读
- javascript - Draggable 在 extjs6.5 中不起作用
- javascript - 无法将额外的道具传递给 this.props.children
- python - 如果/其他循环系统,我将如何修复我的库存?[基于 Python GUI 的冒险游戏]
- corda - 如何在corda上显示创建的流
- android - TextField 未在 Android 上返回时提交
- redis - Lettuce core redis blpop 带来 Type mismatch Can't assign non-array value to an array
- sql - 如何使用基于id的sql server中的列获取行值
- nginx - 使用nginx重定向动态请求
- wordpress - update_post_meta 不适用于 save_post_{post-type}
- php - Laravel查找或失败尝试获取非对象的属性