Reputation: 125902
Suppose I have three tables in my Rails app: cats
, dogs
, and owners
. I want to find all the cats whose owners do not also have dogs.
With SQL, I could do the following:
SELECT
`cats`.*
FROM
`cats`
LEFT JOIN `dogs` ON `cats`.`owner_id` = `dogs`.`owner_id`
WHERE
`dogs`.`id` IS NULL;
However, I'd like to do this as a chainable scope on Cat
. The closest I've gotten so far is Cat.connection.select_all(query_string)
, but that's not chainable.
What's the ActiveRecord way of doing this?
Upvotes: 0
Views: 151
Reputation: 35533
Cat.joins("LEFT JOIN `dogs` ON `cats`.`owner_id` = `dogs`.`owner_id`").where("`dogs`.`id` IS NULL")
Or if you want it as a scope:
scope :cats_without_dogs, joins("LEFT JOIN `dogs` ON `cats`.`owner_id` = `dogs`.`owner_id`").where("`dogs`.`id` IS NULL")
Upvotes: 2