【问题标题】:On polymorphic associations, is it possible to pull in multiple source types on one has_many through query?在多态关联上,是否可以通过查询在一个 has_many 上提取多种源类型?
【发布时间】: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


    【解决方案1】:

    您可以使用以下查询来获取附加到 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
    

    【讨论】:

    • 你好@Shiko,谢谢你的帮助!出于某种原因,第二个方法调用imgs.first.taggable 返回一个NoMethodError, undefined method 'taggable' for <Image>。任何想法如何解决这个问题?
    • 我已经更新了我的原始帖子,提供了一个临时解决方法,以防万一这有助于为您或其他任何人提供一些关于可能解决方案的想法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多