目的
- テーブル作成を行なった際にmigrateでエラーが出た話をまとめる
エラー内容
-
下記コマンドでモデルファイルを作成した。
$ rails g model user name:string
-
その後、下記コマンドでmigreteを実行した。
$ rails db:migrate
-
下記のエラーが発生した
[14:50:10]MacBook-miriwo~/workspace/study/rails/tropical_fish_sns_of_rails$ rails db:migrate == 20200206055010 CreateUsers: migrating ====================================== -- create_table(:users) rails aborted! StandardError: An error has occurred, all later migrations canceled: Mysql2::Error: Table 'users' already exists /Users/admin/workspace/study/rails/tropical_fish_sns_of_rails/db/migrate/20200206055010_create_users.rb:3:in `change' /Users/admin/workspace/study/rails/tropical_fish_sns_of_rails/bin/rails:9:in `<top (required)>' /Users/admin/workspace/study/rails/tropical_fish_sns_of_rails/bin/spring:15:in `<top (required)>' bin/rails:3:in `load' bin/rails:3:in `<main>' Caused by: ActiveRecord::StatementInvalid: Mysql2::Error: Table 'users' already exists /Users/admin/workspace/study/rails/tropical_fish_sns_of_rails/db/migrate/20200206055010_create_users.rb:3:in `change' /Users/admin/workspace/study/rails/tropical_fish_sns_of_rails/bin/rails:9:in `<top (required)>' /Users/admin/workspace/study/rails/tropical_fish_sns_of_rails/bin/spring:15:in `<top (required)>' bin/rails:3:in `load' bin/rails:3:in `<main>' Caused by: Mysql2::Error: Table 'users' already exists /Users/admin/workspace/study/rails/tropical_fish_sns_of_rails/db/migrate/20200206055010_create_users.rb:3:in `change' /Users/admin/workspace/study/rails/tropical_fish_sns_of_rails/bin/rails:9:in `<top (required)>' /Users/admin/workspace/study/rails/tropical_fish_sns_of_rails/bin/spring:15:in `<top (required)>' bin/rails:3:in `load' bin/rails:3:in `<main>' Tasks: TOP => db:migrate (See full trace by running task with --trace)
原因調査
-
下記コマンドを実行して現在のmigrateのステータスを確認した。
$ rails db:migrate:status
-
以前にmigrateを実施した際のmigrationファイルのが無いことが判明した。
[14:52:57]MacBook- miriwo~/workspace/study/rails/tropical_fish_sns_of_rails/db/migrate$ rails db:migrate:status database: tropical_fish_sns_development Status Migration ID Migration Name -------------------------------------------------- up 20200206025324 ********** NO FILE ********** up 20200206025916 ********** NO FILE ********** down 20200206055010 Create users
解決法
-
下記コマンドを実行してDBのリセットを行なった。
$ rails db:migrate:reset
-
DBの状態を確認した。
[14:54:33]MacBook-miriwo~/workspace/study/rails/tropical_fish_sns_of_rails/db/migrate$ rake db:migrate:status (in /Users/admin/workspace/study/rails/tropical_fish_sns_of_rails) database: tropical_fish_sns_development Status Migration ID Migration Name -------------------------------------------------- up 20200206055010 Create users
-
正常に反映されていることをがわかった。