複数のテーブルを参照
モデル生成時に設定する場合
$ 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
参考
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
のような書き方でコネコネすれば出来そうな気がします。