Using includes with multiple associations and separate conditions
Asked Answered
B

2

9

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"

Bi answered 13/1, 2017 at 17:6 Comment(8)
.where('photos.is_processing IS NULL')Convexoconcave
@mudasobwa Thanks.Bi
@mudasobwa I'm still looking to include videos in the query though.Bi
media_items.includes(:photo, :video).where('photos.is_processing IS NULL').rank(:position_in_gallery)Convexoconcave
Unfortunately not: ERROR: missing FROM-clause entry for table "photos"Bi
your query should be 'joins' instead of 'include'. Please check this query joins(:photo, :video).where('photos.is_processing IS NULL').rank(:position_in_gallery)Resentment
Oh, indeed, joins, it’s Friday evening.Convexoconcave
@ShabiniRajadas and @mudasobwa. Got it working with includes. See my answer and thanks.Bi
B
14

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)
Bi answered 13/1, 2017 at 17:28 Comment(0)
G
2

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)
Gemsbok answered 24/7, 2019 at 14:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.