【问题标题】:Rails join table A to table C where A has many B and B has many CRails 将表 A 连接到表 C,其中 A 有很多 B,B 有很多 C
【发布时间】:2025-04-29 05:00:02
【问题描述】:

所以在rails中,我有

class Organization < ActiveRecord::Base
has_many :boxes

class Box < ActiveRecord::Base
has_many :items
belongs_to :organization

class Item < ActiveRecord::Base
belongs_to :box

如果不添加组织上的关联,如何查询属于组织的所有项目?我不想在 Item 中添加 orgaization_id。

【问题讨论】:

    标签: sql ruby-on-rails arel


    【解决方案1】:

    看看has_many :through Association

    在您的情况下,您可以将以下内容添加到您的 Organization 模型中

    has_many :items, through: :boxes
    

    然后你就可以这样写:Organization.find_by(id: ..., name: ....).items

    【讨论】:

    • 这似乎完全合理!我正在考虑加入,但可能没有必要。谢谢