create tableのマイグレーションなのにテーブルがないというエラーでかなり戸惑うが、原因としてはRails 5.0から5.1へのアップデートでPrimary Keyカラムがintからbigintに変更されているので、5.0で作成したテーブルを参照する外部キーを含むマイグレーションを作成すると、もとのテーブルのIDがintであるのに対し、外部キーはbigintでミスマッチになるためエラーになるようだ。
たとえばuser_idを含むcommentsテーブルを作成するマイグレーション。
class CreateComments < ActiveRecord::Migration[5.1]
def change
create_table :comments do |t|
t.references :user, foreign_key: true
end
end
end
Mysql2::Error: Table 'db.comments' doesn't exist: SHOW FULL FIELDS FROM `comments`
.
.
Mysql2::Error: Cannot add foreign key constraint
.
.
abstract_mysql_adapter.rb:876:in `mismatched_foreign_key'
.
.
Mysql2::Error: Cannot add foreign key constraint
.
.
abstract_mysql_adapter.rb:876:in `mismatched_foreign_key'
対策としてはマイグレーションのバージョンを5.0にする
class CreateComments < ActiveRecord::Migration[5.0]
def change
create_table :comments do |t|
t.references :user, foreign_key: true
end
end
end
タグ:Rails