0

My problem is pretty much the same as the answer throughly explained here, except I need to eager load records that are has_one from the polymorphic table.

My models are as follows:

class VisionSource 
  has_one :entity_map, as: :entity_mappable
end

class EntityMap 
  belongs_to :entity_mappable, polymorphic: true
end

How can I then write something verbatim like this EntityMap.includes(:entity_mappable)?

Community
  • 1
  • 1
rico_mac
  • 888
  • 8
  • 22
  • perhaps you can find an answer [here](http://stackoverflow.com/questions/11909257/how-to-eager-load-a-polymorphic-model) – Alex.U Apr 04 '17 at 14:01

1 Answers1

1

Should just work for you out of the box. I suspect it looks like it's not firing because you're not asking for something from the EntityMappable

Try this:

EntityMap.includes(:entity_mappable).map(&:entity_mappable).map(&:class).map(&:name).uniq

I tried this with a couple of classes that use EntityMappable and the above gives this SQL output in rails console:

EntityMap Load (0.9ms) SELECTentity_maps.* FROMentity_mapsORDER BYentity_maps.positionASC CameraShot Load (0.4ms) SELECTvision_sources.* FROMvision_sourcesWHEREvision_sources.typeIN ('CameraShot') ANDvision_sources.idIN (89, 87, 88, 90, 85, 86) ORDER BYvision_sources.positionASC Sound Load (0.3ms) SELECTsounds.* FROMsoundsWHEREsounds.id` = 1

Note that the CameraShot model is a subclass of VisionSource which uses STI (and thus the type field to define itself), while the Sound model effectively looks like this:

class Sound
  has_one :entity_map, as: :entity_mappable
end
TerryS
  • 7,169
  • 1
  • 17
  • 13