LoginSignup
0
0

More than 3 years have passed since last update.

Rails5版 外部キーを設定する5つのやり方

Last updated at Posted at 2019-08-16

環境

  • Rails 5.2.3

外部キーの追加方法 (5パターン)

  1. references (1' はオプション付与したバージョン)
  2. belongs_to ( belongs_to は references の alias です )
  3. <xxx>_id
  4. add_reference (create_table外)
  5. add_foreign_key (create_table外)
  def change
    create_table :transactions do |t|
      # 1. (index も作成してくれます)
      t.references :order, foreign_key: true

      # 1'.
      t.references :order,
        index:       { name: '<index_name>' },
        foreign_key: { to_table: '<actual_table_name>', name: '<foreign_key_name>' },
        null:        false

      # 2. (belongs_to は references の alias です) 
      t.belongs_to :order, foreign_key: true

      # 3.
      t.integer :order_id, index: true
      # `index: true` を付けない場合は、 `create_table` 外で `add_index :transactions, :order_id` とする。
    end

    # 4. 
    add_reference :transactions, :user, foreign_key: true, null: false

    # 5.
    # https://api.rubyonrails.org/?q=add_foreign_key
    # add_foreign_key(from_table, to_table, options = {})
    add_foreign_key :transactions, :orders
  end
0
0
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
0
0