LoginSignup
3
5

More than 5 years have passed since last update.

migration referencesで定義したいフィールド名とforeign_keyのテーブル名が異なっている時の書き方

Last updated at Posted at 2017-02-26

referencesにforeign_keyを指定すると外部キー制約が作れるが、フィールド名と異なっている場合は以下のように書く。

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

これで実用には困らないが、何とかreferencesの一行にうまく書きたい。いろいろ調べたところ foreign_keyに {to_table: :users} というのを与えればできることがわかった。

see. http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_reference

class CreateMessages < ActiveRecord::Migration
  def change
    create_table :messages do |t|
      t.references :sender, foreign_key: {to_table: :users}
    end
  end
end
3
5
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
5