【问题标题】:Get specific type of polymorphic association获取特定类型的多态关联
【发布时间】:2019-09-23 08:40:09
【问题描述】:

我有这个模型

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源设置文章时,pdf仍然找到当html和pdf具有相同的id时

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

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

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

【问题讨论】:

    标签: ruby-on-rails polymorphism ruby-on-rails-5 polymorphic-associations


    【解决方案1】:

    根据 APIdock:

    :foreign_type

    指定用于存储关联对象类型的列,如果这是多态关联。默认情况下,这被猜测为 带有“_type”后缀的关联名称。所以一堂课 定义一个belongs_to :taggable, polymorphic: true 关联将使用 “taggable_type”作为默认值:foreign_type。

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

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

    def html
      source if source_type == "Html"
    end
    
    
    def pdf
      source if source_type == "Pdf"
    end
    

    【讨论】:

    • 啊好的,简单易懂!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多