ポリモーフィック関連付けを使うと、ある1つのモデルが他の複数のモデルに属していることを、1つの関連付けだけで表現できます。
例として、ArticleBlockモデルに複数のモデル(Sentence, Medium,Embed)を関連付けしてみましょう。
※Sentence:文章、Medium:画像、Embed:動画を記事に埋め込みます。
コードの記載
article.rb
class Article < ApplicationRecord has_many :article_tags has_many :tags, through: :article_tags has_many :article_blocks, -> { order(:level) }, inverse_of: :article has_many :sentences, through: :article_blocks, source: :blockable, source_type: 'Sentence' has_many :media, through: :article_blocks, source: :blockable, source_type: 'Medium' has_many :embeds, through: :article_blocks, source: :blockable, source_type: 'Embed' _ . .
article_block.rb
class ArticleBlock < ApplicationRecord belongs_to :article belongs_to :blockable, polymorphic: true, dependent: :destroy . .
sentence.rb
class Sentence < ApplicationRecord has_one :article_block, as: :blockable, dependent: :destroy has_one :article, through: :article_block end
medium.rb
class Medium < ApplicationRecord has_one :article_block, as: :blockable, dependent: :destroy has_one :article, through: :article_block
embed.rb
class Embed < ApplicationRecord has_one :article_block, as: :blockable, dependent: :destroy has_one :article, through: :article_block
図を交えて説明
これにより、sentence media emedを呼び出すことができる。
article = Article.first article.sentence article.media article.emed
他にもこのように呼び出すことができます。
ArticleBlock.first.blockable
Sentence.first.article_block
参考URL