Say I have 2 models, Album and Image, and a join model named AlbumImage (and 3 corresponding tables in the database).
The models share a has-and-belongs-to-many association – Album has many images through album_images, and vice versa.
Tl;dr version
How can I find every image which does not appear within a given album?
Long version
I’m looking for something equivalent to the following SQL:
SELECT * FROM images
WHERE NOT EXISTS (
SELECT * FROM album_images
WHERE album_images.image_id = images.id
AND album_images.album_id = ?
);
i.e. select every image where there does not exist a row in the album_images table with the same image ID and the ID of a given album.
But I unfortunately have no idea how to express this in Rails’ query syntax.
Try this:
Option 1
This approach is better than using NOT EXISTS as sub query result here is cached by DB.
Option 2
Using LEFT OUTER JOIN.
Option 3
If the number of images per album is limited and you dont mind incurring the cost of one extra query: