小さなエンドウ豆

まだまだいろいろ勉強中

1 つのモデル(テーブル)に複数の外部キーをもたせる

テーブルの同じモデルの外部キーを複数もたせる

バージョン rails: 5.1.4

Railsマイグレーションで外部キーを持たせるために必要な記述として以下のように reference を使った方法がある

def change
    create_table :records do |t|
      t.references :users, index: true, foreign_key: true
      t.timestamps null: false
    end
end

ただ、以下のようなモデル(テーブル)を作りたいときにどのようにすればよいかわからなかった…

user_id start_station_id end_station_id
1 2 3
  • user_id は User モデルを参照している
  • start_station_id は Station モデルを参照している
  • end_station_id は Station モデルを参照している

ま、要は 1つのテーブルを複数のカラムで参照したい ということ。

以下のように書くとできたため、記録しておく

class CreateRecords < ActiveRecord::Migration[5.1]
  def change
    create_table :records do |t|
      t.references :users, index: true, foreign_key: true
      t.references :start_station
      t.references :end_station
      t.timestamps null: false
    end
    add_foreign_key :records, :stations, column: :start_station_id
    add_foreign_key :records, :stations, column: :end_station_id
  end
end

参考:

Railsマイグレーションのindex、foreign_keyの設定

複合外部キーなども設定できるらしく知らなかった…
Rails は直感的に書くとできるのでありがたい