获取特定类型的多态关联

Get specific type of polymorphic association

我有这个型号

class Article
  belongs_to :source, polymorphic: true
  belongs_to :html, foreign_type: "Html", foreign_key: "source_id"
  belongs_to :pdf, foreign_type: "Pdf", foreign_key: "source_id"
end

当我用 html 来源设置文章时,当 html 和 pdf 具有相同的 id 时 仍然可以找到 pdf

html.id
=> 1
pdf.id
=> 1

article = Article.create!(source: html)
article.pdf.id
=> 1

我做错了什么? foreign_type 不是告诉 Rails 多态关联要匹配什么吗?

根据 APIdock:

:foreign_type

Specify the column used to store the associated object’s type, if this is a polymorphic association. By default this is guessed to be the name of the association with a “_type” suffix. So a class that defines a belongs_to :taggable, polymorphic: true association will use “taggable_type” as the default :foreign_type.

因此,您应该在 source 关联中使用 foreign_type 来指定存储关联对象类型的列。

我认为您需要 htmlpdf 两种方法,因此您可以在源为 HtmlPdf 时使用它。在这种情况下,我认为你应该为它创建两个方法,例如:

def html
  source if source_type == "Html"
end


def pdf
  source if source_type == "Pdf"
end