rails db:migrate をしたらMysql2::Error: Table 'テーブル名' doesn't exist と怒られる問題


何が起こったのか?

migrationファイルを追加していつものように rails db:migrate を叩いたところ、以下のように怒られた。

StandardError: An error has occurred, all later migrations canceled:

Mysql2::Error: Table 'Mysql内のテーブル名' doesn't exist
<略>
Caused by:
ActiveRecord::StatementInvalid: Mysql2::Error: Table 'Mysql内のテーブル名' doesn't exist

ActiveRecord::StatementInvalidとは?

簡潔に言えば「記述が違うぞ💢」ということ。

※Mysql内のテーブル名は % rails db を叩いてMysqlに入り、SHOW TABLES; で確認できます。

mysql> SHOW TABLES;

確認すべきところ

・ migrationファイルのテーブル名
→ タイポしていないかどうか(ex:スペルミスや大文字になっていないかなど)

ちなみに自分の場合はsorcery_coreのmigrationファイル内の「create_table :users」が大文字になっていたことが原因でした。

変更前
class SorceryCore < ActiveRecord::Migration[6.0]
  def change
    create_table :Users do |t|
      t.string :email,            null: false
      t.string :crypted_password
      t.string :salt

      t.timestamps                null: false
    end

    add_index :users, :email, unique: true
  end
end

変更後
class SorceryCore < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string :email,            null: false
      t.string :crypted_password
      t.string :salt

      t.timestamps                null: false
    end

    add_index :users, :email, unique: true
  end
end

タイポに気をつけて

初歩的ではあるものの、意外と気付き難いが故に根深い問題の1つではないでしょうか?
こまめに確認して、どこに問題があるのかを探しやすくすることが大切だと痛感しました。