shou2017.com
JP

Mysql2::Error: Table 'products' already exists and how to resolve it

Wed Feb 14, 2018
Sat Aug 10, 2024

When attempting to run a migration, the following error appeared:

$ 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

~omitted~

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

This error means that the table already exists. To resolve this, simply delete the table.

In the terminal, enter the following:

$ rails db

Then, when mysql> is displayed, enter SHOW TABLES;:

mysql> SHOW TABLES;

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

Since we want to delete the products table, enter the following:

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

Verify that the table has been deleted:

mysql> SHOW TABLES;
+------------------------------+
| Tables_in_sample_development |
+------------------------------+
| ar_internal_metadata         |
| schema_migrations            |
+------------------------------+
2 rows in set (0.00 sec)

Once confirmed, exit MySQL:

mysql> exit

Finally, run the migration again:

$ rake db:migrate

That’s it!

See Also