如何查询无关联Bar的Foo实例?(多态关联场景)
查询无关联Bar的Foo实例解决方案
嘿,我懂你要的效果!你之前用Foo.where(barable: nil)不行是因为barable并不是Foo模型的字段——它是Bar那边的多态关联字段,用来指向Foo(或者其他模型)的。下面给你两种靠谱的实现方式:
方法1:LEFT JOIN + 筛选空关联
这种写法直观易懂,适合数据量不大的场景:
Foo.left_joins(:bars).where(bars: { id: nil })
原理是left_joins会把所有Foo都拉出来,哪怕没有对应的Bar;之后通过bars.id: nil筛选出那些完全没有关联Bar的Foo记录。
方法2:NOT EXISTS子查询(性能更优)
如果你的数据量比较大,这种写法的查询效率会更高,因为数据库不需要做全表连接:
Foo.where.not( id: Bar.select(:barable_id).where(barable_type: 'Foo') )
原理是先通过子查询找出所有已经关联了Bar的Foo的ID,然后用where.not排除这些ID,剩下的就是没有任何Bar关联的Foo了。
补充:你的模型与数据表结构
方便参考,这里整理你提供的代码结构:
Foo模型
class Foo < ApplicationRecord has_many :bars, as: :barable end
Bar模型
class Bar < ApplicationRecord belongs_to :barable, polymorphic: true end
数据表结构
Foo(id: integer, name: string, created_at: datetime, updated_at: datetime) Bar(id: integer, barable_type: string, barable_id: string, created_at: datetime, updated_at: datetime)
内容的提问来源于stack exchange,提问作者ferne97
相关产品推荐
相关产品推荐

