【发布时间】:2020-03-17 17:17:30
【问题描述】:
在处理多态关联时,是否可以有一个 has_many through 查询来拉入所有可用的 source_types?
到目前为止,我的理解是每种源类型都需要自己的查询方法,正如我在 Image 模型中展示的那样
image.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)
仍然不是一个完整的答案,但在此期间这是一个临时解决方法。
【问题讨论】:
标签: ruby-on-rails activerecord has-many-through polymorphic-associations