1
0

More than 3 years have passed since last update.

Railsで外部キー追加時に「型の不整合」で失敗する場合の対応

Last updated at Posted at 2019-11-21

環境

  • 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
1
0
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
1
0