Search code examples
ruby-on-railsrubyruby-on-rails-4activerecordactive-record-query

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"


Solution

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