LoginSignup
59

More than 5 years have passed since last update.

Railsマイグレーションの外部キー制約を表現するreferencesについて

Posted at

CompanyとProjectの一対多の関係性

この図のような関連性で外部キー制約を表現するには

class CreateProjects < ActiveRecord::Migration
  def change
    create_table :projects do |t|
      t.references :company
      t.timestamps null: false
    end
  end
end

と書けばよさそうですが、これでは外部キー制約になりません。foreign_key: trueを付ける必要があります。

class CreateProjects < ActiveRecord::Migration
  def change
    create_table :projects do |t|
      t.references :company, foreign_key: true
      t.timestamps null: false
    end
  end
end

また次のような同じモデルを複数カラムから参照するような関連性でもreferencesは使えません。

MessageテーブルとUserテーブル

こうしたケースでは、add_foreign_keyを使います。

class CreateMessages < ActiveRecord::Migration
  def change
    create_table :messages do |t|
      t.references :sender
      t.references :recipient
      t.timestamps null: false
    end
    add_foreign_key :messages, :users, column: :sender_id
    add_foreign_key :messages, :users, column: :recipient_id
  end
end

参考: Rails:外部キー制約をマイグレーションで表現する方法

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
59