3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsのポリモーフィック関連

Posted at

あまり好みではないのだが、モデルAに対し、
モデルBとモデルCのどちらかが関連づけられる、という設計がある。
そんな時にはポリモーフィック関連を使う。

各マイグレーションファイル
class CreateCompanies < ActiveRecord::Migration
  def change
    create_table :companies do |t|
      t.string :name, null: false, default: ""

      t.timestamps
    end
  end
end

class CreatePeople < ActiveRecord::Migration
  def change
    create_table :people do |t|
      t.string :name, null: false, default: ""

      t.timestamps
    end
  end
end

class CreateContracts < ActiveRecord::Migration
  def change
    create_table :contracts do |t|
      t.integer  :partner_id,   null: false
      t.string   :partner_type, null: false, default: ""
      t.string   :name,         null: false, default: ""

      t.timestamps
    end
  end
end
各モデルファイル
class Company < ActiveRecord::Base
  has_many :contracts, as: :partners
end

class Person < ActiveRecord::Base
  has_many :contracts, as: :partners
end

class Contract < ActiveRecord::Base
  belongs_to :partner, polymorphic: true
end

この時、以下のように使う。

使い方
    company = Company.create(name: "会社A")
    person  = Person.create(name: "個人A")
    cont1 = Contract.create(partner: company, name: "契約A")
    cont2 = Contract.create(partner_id:   person.id,
                            partner_type: person.class.name,
                            name: "契約B")
3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?