rails 范围检查关联是否不存在 [英] rails scope to check if association does NOT exist

查看:46
本文介绍了rails 范围检查关联是否不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望编写一个范围来返回所有没有特定关联的记录.

I am looking toward writing a scope that returns all records that do not have a particular association.

foo.rb

class Foo < ActiveRecord::Base    
  has_many :bars
end

bar.rb

class Bar < ActiveRecord::Base    
  belongs_to :foo
end

我想要一个可以找到所有没有有任何barsFoo's的范围.使用 joins 很容易找到具有关联的那些,但我还没有找到相反的方法.

I want a scope that can find all of the Foo's that dont have any bars. It's easy to find the ones that have an association using joins, but I haven't found a way to do the opposite.

推荐答案

Rails 4 让这一切变得太简单了 :)

Rails 4 makes this too easy :)

Foo.where.not(id: Bar.select(:foo_id).uniq)

这会输出与 jdoe 的答案相同的查询

this outputs the same query as jdoe's answer

SELECT "foos".* 
FROM "foos" 
WHERE "foos"."id" NOT IN (
  SELECT DISTINCT "bars"."foo_id"
  FROM "bars" 
)

作为范围:

scope :lonely, -> { where.not(id: Bar.select(:item_id).uniq) }

这篇关于rails 范围检查关联是否不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆