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

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

问题描述

我找对写作的作用域返回所有记录不具有特定关联。

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

我要一个范围,可以发现所有的的Foo的不要的任何酒吧。人们很容易发现,在使用关联加入的那些,但我还没有找到一种方法,做相反的事情。

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.

推荐答案

4的Rails使这太容易了:)

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) }

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

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