環境
- Rails 5.2.2.1
エラー内容
add_foreign_key
などで外部キー制約をつけようとすると、rails db:migrate
が失敗して以下のエラーが出る。
Mysql2::Error: Referencing column 'user_id' and referenced column 'id' in foreign key constraint 'fk_rails_85591c599e' are incompatible.
原因
「外部キー(user_id
)」と「参照先テーブルのカラム(users
テーブルのid
)」の型が異なっている。
よくある例としては、Rails5.1
からid
カラムがbigint
になったが、過去に作成したテーブルのid
カラムがint
のままの場合。
対応方法
id
カラムをbigint
にする。
db/migrate/20190000000000_xxx.rb
class SomeMigrationFile < ActiveRecord::Migration[5.2]
def change
reversible do |dir|
dir.up do
change_column :users, :id, :bigint, auto_increment: true
end
dir.down do
change_column :users, :id, :int, auto_increment: true
end
end
end
end