急切加载'has

系统教程 行业动态 更新时间:2024-06-14 16:53:07
急切加载'has_one'的ActiveRecord多态关联(eager load ActiveRecord polymorphic associations that are 'has_one')

我的问题与这里解释的答案几乎相同,除了我需要从多态表中加载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 end

How 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 end

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

更多推荐

本文发布于:2023-04-05 21:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/ab4538ca2b3ddb8994ab1502c52a1c48.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:急切   加载

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!