bokunonikki.net
JP / EN

Mysql2::Error: Table '' already existsと表示されてしまった時の対処法

Wed Feb 14, 2018
Wed Feb 14, 2018

マイグレーションをしようとした時に下のようなエラーが表示された。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$ rake db:migrate
== 20180214062508 CreateProducts: migrating ===================================
-- create_table(:products)
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

Mysql2::Error: Table 'products' already exists: CREATE TABLE `products` (`id` bigint NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` varchar(255), `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL) ENGINE=InnoDB

〜省略〜

Tasks: TOP => db:migrate
(See full trace by running task with --trace)

このエラーの意味は、もうすでに同じtableがあるんですよと言った感じのエラー。 この状況になったら単純にtableを削除してあげたら問題ない。

ターミナルで以下のように入力する。

1
$ rails db

その後、mysql>が表示されるので、そこでSHOW TABLES;と入力する。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
mysql> SHOW TABLES;

+------------------------------+
| Tables_in_sample_development |
+------------------------------+
| ar_internal_metadata         |            
| products                     |
| schema_migrations            |
+------------------------------+
3 rows in set (0.00 sec)

今回は、productsのtableを削除したいので、以下のように入力する。

1
2
mysql>drop table products;
Query OK, 0 rows affected (0.01 sec)

ちゃんと削除できたのか確認します。

1
2
3
4
5
6
7
8
mysql> SHOW TABLES;
+------------------------------+
| Tables_in_sample_development |
+------------------------------+
| ar_internal_metadata         |
| schema_migrations            |
+------------------------------+
2 rows in set (0.00 sec)

ちゃんとできていることを確認できたので、exitで抜けます。

1
mysql>exit

あとは、

1
$ rake db:migrate

以上、終わり。

See Also