在多态关联上,是否可以通过查询在一个has_many上引入多个源类型



在处理多态关联时,是否可以使用has_many直通查询来获取所有可用的source_types?

到目前为止,我的理解是,每个源类型都需要自己的查询方法,如我在图像模型中所示

图像.rb

has_many :image_tags
has_many :tags, through: :image_tags, source: :taggable, source_type: 'Tag'
has_many :people, through: :image_tags, source: :taggable, source_type: 'Person'
has_many :businesses, through: :image_tags, source: :taggable, source_type: 'Business'
...

tag.rb

has_many :image_tags, as: :taggable
has_many :images, through: :image_tags

image_tag.rb

belongs_to :image
belongs_to :taggable, polymorphic: true
def build_taggable(params)
self.taggable = taggable_type.constantize.new(params)
end

然而,我想做的是创建一个查询方法,它可以拉入所有相关的记录,而不管它们可能属于哪个source_type

只是大声思考一下,这可能涉及创建某种直接作用于ImageTags表的原始SQL联接吗?还是有一种更Railsy/ActiveRecordy的方式来接近它?


更新20200319:

从那以后,我找到了一种将各个方法聚合在一起的方法,但这仍然需要创建独特的方法。

def taggables 
tags + people + businesses
end

这允许类似的东西

i = Image.first
i.crops.map(&:taggables)

仍然不是一个完全的答案,但这是一个暂时的解决办法。

您可以使用以下查询来获取附加到image_tag的任何关联:

# get all images with all associations
imgs = Image.includes(image_tags: :taggable)
# to get value polymorphic association regardless of it's source
# taggable may be tags, people or businesses
poly_assoc = imgs.first.taggable # associaiton of first record
# to get the association type
pp pol_assoc.to_s.class.to_s

相关内容

最新更新