Rails Query基于非主键列关联Foo、Bar且无需关联Profile表的实现方法
方案1:单次查询直接写自定义JOIN
不需要修改现有模型代码,直接在joins方法传入SQL片段即可,生成的SQL完全符合要求,不会关联Profile表:
Foo.joins("INNER JOIN bar ON foo.profile_id = bar.profile_id")
方案2:定义关联实现复用
如果需要频繁使用Foo和Bar的关联,可以直接在模型层添加自定义关联,跳过Profile层:
class Foo < ApplicationRecord belongs_to :profile # 新增直接关联Bar的规则,通过两边的profile_id匹配 has_many :bars, foreign_key: :profile_id, primary_key: :profile_id end
后续可以直接用Rails原生关联语法查询,用法和普通关联完全一致,也不会触发Profile表的JOIN:
# 基础关联查询 Foo.joins(:bars) # 支持链式附加查询条件 Foo.joins(:bars).where(bars: { status: 1 })
如果需要Bar到Foo的反向关联,同理在Bar模型中添加对应配置即可:
class Bar < ApplicationRecord belongs_to :profile has_many :foos, foreign_key: :profile_id, primary_key: :profile_id end
内容的提问来源于stack exchange,提问作者Stefan Collier
相关产品推荐
相关产品推荐

