rails scope to check if association does NOT exist

Rails 4 makes this too easy 🙂

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

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

And as a scope:

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)