【问题标题】:How to use ActiveRecord's usual has_many methods with polymorphic associations?如何将 ActiveRecord 的常用 has_many 方法与多态关联一起使用?
【发布时间】:2020-03-16 19:10:01
【问题描述】:

我正在尝试重新构建我的一些模型以包含多态关联,但我遇到了很多障碍。

即使像Tag.images << @crop_image 这样简单的东西也会返回错误:

ActiveModel::UnknownAttributeError - unknown attribute 'tag_id' for ImageTag.

我需要对collection<< 方法进行修改,以便它正确使用与多态关联一起使用的:taggable_id:taggable_type 列吗?

或者我在尝试设置模型时是否存在错误? Rails 5 Way 谈到在模型中指定 sourcesource_type 选项,我已经尝试在此处实施这些建议。

image.rb

has_many :image_tags
has_many :tags, through: :image_tags, source: taggable, source_type: 'Tag'

image_tag.rb

belongs_to :image
belongs_to :taggable, polymorphic: true

def build_taggable(params)
  self.taggable = taggable_type.constantize.new(params)
end

tag.rb

has_many :image_tags
has_many :images, through: :image_tags, source: :taggable, source_type: 'Image'

【问题讨论】:

    标签: ruby-on-rails collections has-many-through polymorphic-associations


    【解决方案1】:

    啊哈!原来我没有正确配置has_many 关联。 as: :taggable 选项应该放在连接表上。

    应该是:

    image.rb

    has_many :image_tags, as: :taggable
    has_many :tags, through: :image_tags
    

    tag.rb

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

    稍后我可能仍需要指定 sourcesource_type 选项,但此修复程序重新投入使用!


    更新 20200317:

    好的,所以我觉得我现在对情况有了更好的了解。由于需要单独设置每个相关联的方法,因此使用带有直通表的多态会有点失去光泽。这就是sourcesource_type 选项发挥作用的地方。

    因此,如果我想让用户能够调用image.tags,我需要为模型提供更多信息,以便它知道.tags 实际上意味着什么。它看起来像这样:

    has_many :tags, through: :taggable, source_type: 'Tag'
    

    这一切都很好,但是如果用户想一口气调用所有不同类型的可标记对象怎么办?截至目前,我不知道这是否可能。也许您可以“读入”列中存在的唯一值,然后以某种方式依次调用它们?

    --或者!--

    也许你完全绕过了 activerecord 查询方法的东西,只是简单地通过 SQL 查询连接表?这可能是一个更好的方法...

    但这可能不是重点……我目前知道的唯一方法是为每种类型设置自定义查询方法。所以你最终会得到类似的东西

    has_many :people, through: :taggable, source_type: 'Person'
    has_many :businesses, through: :taggable, source_type: 'Business'
    

    然后您必须单独调用它们,然后将它们聚合到一个巨大的数组状结构中。

    【讨论】:

      猜你喜欢
      • 2011-09-28
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多