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