ポリモーフィック関連付けについて

【結論】

ポリモーフィック関連付けとは
 ある特定のモデルが他の複数のモデルに属している事を
 一つの記述だけで表す手法

・画像などを一つのモデル(テーブル)で
 集約して管理したい場合に有用

ポリモーフィック関連付けの元となるテーブルの
 外部キーにimageableを設定する事で
 親モデルとレコードの判別が可能になる

【目次】

【本題】

ポリモーフィック関連付けについて

ポリモーフィック関連付けとは、
ある一つのモデルが他の複数のモデルに属している事を
一つの記述だけで表す手法です。

例えば、下記の様なアソシエーションです。

class Image < ApplicationRecord
  belongs_to :imageable, polymorphic: true
end
 
class User < ApplicationRecord
  has_many :images, as: :imageable
end
 
class Post < ApplicationRecord
  has_many :images, as: :imageable
end

Imageの関連付けの記述は一つだけですが
これでuserpost
それぞれに従属している関係を表せます。

また、上記ではImageを例に出しましたが、
画像の様に、一つのテーブルで集約して管理した方が
拡張性/メンテナンス性の観点で優れている場合に、
この方法が採用されます。

外部キーの設定

なお、ポリモーフィック関連付けでは
外部キーの設定の仕方も独特です。

class CreateImages < ActiveRecord::Migration[5.0]
  def change
    create_table :images do |t|
      t.references :imageable, polymorphic: true, index: true
      t.text :image_data
      t.string :image_relation, limit: 120
      t.timestamps
    end
  end
end

上記の例の様にt.references :imageable, polymorphic: true, index: trueとすると、
imageable_typeimageable_idというカラムが生成されます。

これらによって、どのテーブルのどのレコードと
関連付いてのかを判別する事が可能となります。

参考情報

Active Record の関連付け - Railsガイド