Search code examples
ruby-on-railspolymorphismruby-on-rails-5polymorphic-associations

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.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?


Solution

  • According to 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.

    So, you should use foreign_type in the source association to specify what column stores the associated object's type.

    I think you want two methods html and pdf, so you can use it when the source is either Html or 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