5
6

More than 3 years have passed since last update.

【Rails】1つのテーブルに複数の外部キーを設定

Last updated at Posted at 2020-01-04

複数のテーブルを参照

モデル生成時に設定する場合

$ rails g model Song user:references mc:references song
migrationファイル
class CreateSongs < ActiveRecord::Migration[6.0]
  def change
    create_table :songs do |t|
      t.references :user, foreign_key: true
      t.references :mc, null: false, foreign_key: true
      t.string :song

      t.timestamps
    end
  end
end

後から追加する場合

add_foreign_key :参照元のテーブル名, :参照したいテーブル名, column: :参照元につける外部キー名
migrationファイル
add_foreign_key :songs, :users, column: :user_id
add_foreign_key :songs, :mcs, column: :mc_id

参考

【rails5】テーブルに複数の外部キーを追加する

1つのテーブルを2つのカラムで参照

モデル作成時のコマンドでは外部キーを指定せず、作成されたマイグレーションファイルを手動で変更しました。

rails g model Video url
migrationファイル
class CreateVideos < ActiveRecord::Migration[6.0]
  def change
    create_table :videos do |t|
      t.references :mc1
      t.references :mc2
      t.string :url

      t.timestamps
    end
    add_foreign_key :videos, :mcs, column: :mc1_id
    add_foreign_key :videos, :mcs, column: :mc2_id
  end
end

試していませんが、既存のテーブルに外部キーを追加する時にもadd_foreign_key :videos, :mcs, column: :mc1_idのような書き方でコネコネすれば出来そうな気がします。

参考

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

5
6
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
5
6