Ruby on rails 获取多态关联的特定类型
我有这个型号Ruby on rails 获取多态关联的特定类型,ruby-on-rails,polymorphism,ruby-on-rails-5,polymorphic-associations,Ruby On Rails,Polymorphism,Ruby On Rails 5,Polymorphic Associations,我有这个型号 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仍然可以找到: htm
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
我做错了什么?告诉Rails多态关联要匹配什么的外来类型不是吗?根据APIdock:
:外来类型
如果是多态关联,请指定用于存储关联对象类型的列。默认情况下,这被认为是
带有“\u type”后缀的关联的名称。那么一节课
定义将使用的属于:可标记、多态:真实关联
默认为“标记类型”:外部类型
因此,您应该在源
关联中使用外来类型
,以指定存储关联对象类型的列
我认为您需要两种方法html
和pdf
,因此当源代码是html
或pdf
时可以使用它。在这种情况下,我认为您应该为它创建两种方法,例如:
def html
source if source_type == "Html"
end
def pdf
source if source_type == "Pdf"
end
啊,好吧,这很简单,也很容易理解!谢谢