ポリモーフィックアソシエーション

ポリモーフィズムとは

rails でリレーション(1対多関係) を組む際に、一つのモデルに対して 複数のモデル リレーション を組む際に非常に便利です。

利点としては以下の通りです。

  • リレーション元のデータがどの モデル ID と紐付いているか、保存されている。
  • ↑により、外部キーは一元管理される。(複数の外部キー作らなくて良い!)

実行してみる

# relation
class Review < ActiveRecord::Base
  belongs_to :resource, :polymorphic => true
end

class Artist < ActiveRecord::Base
  has_many :reviews, :as => :resource
end

class Live < ActiveRecord::Base
  has_many :reviews, :as => :resource
end

class Disc < ActiveRecord::Base
  has_many :reviews, :as => :resource
end
#実行ファイル

disc = Disc.create(name: 'disc_test', info: 'disc_info')
disc.reviews.create(review_content: 'disc_review')

live = Live.create(name: 'live_test', info: 'live_info')
live.reviews.create(review_content: 'live_review')

artist = Artist.create(name: 'artist_test', info: 'artist_info')
artist.reviews.create(review_content: 'artist_review')

結果

Review f:id:jesushill:20180211142319p:plain

Artist(抜粋) f:id:jesushill:20180211142428p:plain

link

今回作成したプログラム Rails ガイド