Rails 6.1 ActiveRecord跨多层关联实现Person has_many :ceos方案问询
实现方案
该需求可通过ActiveRecord原生的has_many :through关联串联实现,无需自定义复杂查询。
1 补全全链路关联声明
先确保所有中间模型的关联按以下规则声明:
# CEO 模型 class CEO < ApplicationRecord has_many :investing_companies end # InvestingCompany 模型 class InvestingCompany < ApplicationRecord belongs_to :ceo has_many :toy_makers end # ToyMaker 模型 class ToyMaker < ApplicationRecord belongs_to :investing_company has_many :pet_toys # 声明直达CEO的关联,方便中间层调用 has_one :ceo, through: :investing_company end # PetToy 模型 class PetToy < ApplicationRecord belongs_to :pet belongs_to :toy_maker # 声明直达CEO的关联,替代原delegate实现,适配has_many串联规则 has_one :ceo, through: :toy_maker end # Pet 模型 class Pet < ApplicationRecord belongs_to :person has_many :pet_toys end
2 Person模型声明最终关联
直接通过多层through串联即可:
class Person < ApplicationRecord has_many :pets has_many :pet_toys, through: :pets # 最终关联:通过pet_toys链路关联到所有对应的CEO has_many :ceos, through: :pet_toys end
可选优化
如果需要避免同一个CEO因关联多个宠物玩具重复返回,可添加去重逻辑:
has_many :ceos, through: :pet_toys, -> { distinct }
验证方式
执行Person.first.ceos.to_sql即可输出生成的关联查询SQL,确认已自动拼接4层关联的JOIN逻辑,符合预期。
内容的提问来源于stack exchange,提问作者ForeignOrchid
相关产品推荐
相关产品推荐

