Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using includes with multiple associations and separate conditions

I have the following query in my Gallery model:

media_items.includes(:photo, :video).rank(:position_in_gallery)

My Gallery Model has_many Media Items which each have either a Photo or Video association.

So far this works fine. It returns all the media_items including their photo or video association, ordered by the position_in_gallery attribute of the media_item.

However I now have a requirement to limit the Photos returned by this query to only those with an attribute of is_processing that is nil.

Is it possible to make this same query but with a condition on the photos returned equivalent to:

.where(photo: 'photo.is_processing IS NULL')

Note that all the videos should be returned regardless and do not include an is_processing attribute.

I've tried @mudasbwa's suggestion:

includes(:photo, :video).where('photos.is_processing IS NULL').rank(:position_in_gallery)

but it gets me:

ERROR: missing FROM-clause entry for table "photos"

like image 876
Undistraction Avatar asked Jan 13 '17 17:01

Undistraction


2 Answers

Turns out I was on the right track. I needed to use references():

media_items.includes(:photo, :video).where('photos.is_processing IS NULL').references(:photo).rank(:position_in_gallery)
like image 85
Undistraction Avatar answered Nov 15 '22 21:11

Undistraction


If you want to use pure ActiveRecord with no SQL strings:

media_items.includes(:photo, :video).where(photos: { is_processing: nil }).rank(:position_in_gallery)
like image 23
jamesmarkcook Avatar answered Nov 15 '22 22:11

jamesmarkcook