LoginSignup
18
11

More than 3 years have passed since last update.

はじめに

モデルのpolymorphicに関してちょっとまとめます

マイグレーションファイルの作成

commentモデルを下記の様に作成します。

class CreateComments < ActiveRecord::Migration[6.0]
  def change
    create_table :comments do |t|
      t.references :target, null: false, polymorphic: true
      t.text :body, null: false

      t.timestamps
    end
  end
end

t.references :target, null: false, polymorphic: trueこれによって、target_typetarget_idカラムが追加されます。

target_typeには対象のモデル名が入り、target_idには対象のデータのidが入ります。
これによって、どのモデルとでも関連を結ぶことができます。

モデルファイルの修正

commentモデルとuserモデルが紐づく場合

commentのモデルファイルには

class Comment < ApplicationRecord
  belongs_to :target, polymorphic: true
end

と記載し、userのモデルファイルには

class User < ApplicationRecord
  has_many :comments, :as => :target
end

と記載します。

データの作成

user.comments.create(body: 'hello')

この様にしてデータを作成できます。

もちろん、別のモデルでもhas_many :comments, :as => :targetと記載するだけで、紐付けをすることができるので便利です。

終わりに

active storageに関してもこのポリモーフィックを使って、どのモデルに対しても画像を紐付けれる様にしています。

18
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
11