I have a Gallery that has_many MediaItems, each of which has_one Video or Photo.
I'm currently using the following query:
MediaItem.includes(gallery: {media_items: [:photo, :video]}).featured.rank(:position_in_featured)
However given that the media item will only ever have a Video or a Photo, I am always left with an unused eager load for whichever it doesn't have.
Is there a more efficient way of querying to avoid this unneeded include?
Note: I don't need a solution that involves Polymorphic associations. In this case they introduce too much complexity to other queries and don't fit the data model.
The best way to do this would probably be changing your data model to a polymorphic relationship and using a
belongs_toassociation inMediaItemFor this to work you need to have a type
media_content_idandmedia_content_typecolumns onMediaItem.EDIT: There is even a note in the docs that eager loading should work in your case in the last paragraph of this section: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#module-ActiveRecord::Associations::ClassMethods-label-Eager+loading+of+associations