我的问题与这里解释的答案几乎相同,除了我需要从多态表中加载has_one记录。
我的模型如下:
class VisionSource has_one :entity_map, as: :entity_mappable end class EntityMap belongs_to :entity_mappable, polymorphic: true end我怎么能像这个EntityMap.includes(:entity_mappable)一样逐字写东西?
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 endHow can I then write something verbatim like this EntityMap.includes(:entity_mappable)?
最满意答案
应该只为您开箱即用。 我怀疑它似乎没有被解雇,因为你不是要求EntityMappable提供的东西
尝试这个:
EntityMap.includes(:entity_mappable).map(&:entity_mappable).map(&:class).map(&:name).uniq
我尝试了几个使用EntityMappable的类,上面在rails控制台中给出了这个SQL输出:
EntityMap Load (0.9ms) SELECT entity_maps .* FROM entity_maps ORDER BY entity_maps . 位置ASC CameraShot Load (0.4ms) SELECT vision_sources .* FROM vision_sources WHERE vision_sources . 输入IN ('CameraShot') AND vision_sources . id IN (89, 87, 88, 90, 85, 86) ORDER BY 89,87,88,90,85,86 IN (89, 87, 88, 90, 85, 86) ORDER BY vision_sources . 位置ASC Sound Load (0.3ms) SELECT声音.* FROM声音发出声音. id` = 1
请注意,CameraShot模型是VisionSource的子类,它使用STI(因此类型字段定义自己),而Sound模型实际上如下所示:
class Sound has_one :entity_map, as: :entity_mappable endShould 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更多推荐
发布评论