获取所有在belongs_to关系中引用(或者不是)的记录的有效方法是什么?

时间:2017-01-31 17:03:55

标签: sql ruby-on-rails ruby

如果我有一个模型A和一个模型B,其中B属于A,找到所有至少有一个B的A的最有效方法是什么?同样,找到相反的最有效率的是什么(所有A'没有B')。

1 个答案:

答案 0 :(得分:1)

试试这个:

# All A's that have no B's
A.eager_load(:B).where('B.id is null') 
# or
A.eager_load(:B).where(B: { id: nil })

# all A's that have at least one B
A.joins(:B).where('B.id is not null')
# or this should already do the trick because inner join will ignore null records in B
A.joins(:B)

请务必将B更改为您的表格名称。