[英]Get specific type of polymorphic association
I have this model 我有这个模特
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
When I set an article with an html source, pdf
is still found when html and pdf have the same id : 当我设置与HTML源代码的文章, pdf
仍然发现当HTML和PDF具有相同的ID:
html.id
=> 1
pdf.id
=> 1
article = Article.create!(source: html)
article.pdf.id
=> 1
What am I doing wrong? 我究竟做错了什么? Isn't the foreign_type
that tells Rails what to match for the polymorphic association? 这不是foreign_type
告诉Rails多态关联要匹配什么吗?
According to APIdock: 根据APIdock:
:foreign_type :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. 默认情况下,它被认为是后缀为“ _type”的关联的名称。 So a class that defines a belongs_to :taggable, polymorphic: true association will use “taggable_type” as the default :foreign_type. 因此,定义一个属下属属的:taggable,多态性:true关联的类将使用“ taggable_type”作为默认的:foreign_type。
So, you should use foreign_type
in the source
association to specify what column stores the associated object's type. 因此,您应该在source
关联中使用foreign_type
来指定存储关联对象类型的列。
I think you want two methods html
and pdf
, so you can use it when the source is either Html
or Pdf
. 我认为您需要html
和pdf
两种方法,因此当源是Html
或Pdf
时可以使用它。 In this case, I think you should create two methods for it, for example: 在这种情况下,我认为您应该为此创建两个方法:
def html
source if source_type == "Html"
end
def pdf
source if source_type == "Pdf"
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.