hirolibe / hiro-blogapp

0 stars 0 forks source link

気づき(マイグレーションファイルのreferences) #45

Open hirolibe opened 1 month ago

hirolibe commented 1 month ago

foreign_key: { to_table: :users } の記載がない場合、Railsはデフォルトで外部キーの参照先テーブル名をカラム名から推測する 下記コードの場合、followingsテーブルやfollowersテーブルの主キーを外部キーと推測するが、今回はこれらのテーブルは作成していないため、マイグレーション実行時にエラーが生じる

class CreateRelationships < ActiveRecord::Migration[6.0]
  def change
    create_table :relationships do |t|
      t.references :following, null: false, foreign_key: { to_table: :users }
      t.references :follower, null: false, foreign_key: { to_table: :users }

      t.timestamps
    end
  end
end