Troubleshooting Rails Migrations

I’m not sure why this worked, but if it can help anyone else then here it goes . . .

My rails app decided to throw a hissy fit at me by refusing to let me run rake db:migrate because (as it claimed)

rake aborted!
An error has occurred, all later migrations canceled:

Mysql::Error: Table ‘states’ already exists: CREATE TABLE `states` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `name` varchar(255), `continent_id` int(11) NOT NULL, `notes` text, `created_at` datetime, `updated_at` datetime, FOREIGN KEY (continent_id) REFERENCES continents (id)) ENGINE=InnoDB

This was deeply weird because that migration was the 3rd of about 30 migrations in my application. Rails had happily skipped over it in the many months since I had first run it to create the states table, moving directly to the new migrations and running them. Something was wrong, but I had no idea what. After many hours of frustration I stumbled across a viable (albeit hacky) solution to my problem.

Looking at the following thread on Stack Overflow (http://stackoverflow.com/questions/842162/is-rake-dbmigrate-the-correct-command-to-re-sync-schema-rb-with-your-database-sc), I saw that if I commented out the create table in the failing migration and ran rake db:migrate again rails would skip the troubled migration. I meant to do this, but in my haste I only commented out the lines the describing the table, forgetting to comment out the “create_table” and its associated “end” lines of code.

I ran rake db:migrate before I realized this and got the following:

(in /Users/jabauer/pq_eafsd)
== CreateStates: migrating ===================================================
== CreateStates: migrated (0.0000s) ==========================================

I quickly realized my mistake and took out the comments, hoping to put the fields back in the table. When I did so, rake db:migrate ran perfectly. I am pretty new to rails, so I have no idea why this worked or if it is a replicable solution. However, I am offering it to you in the hopes that it will work, save you time, and keep you from having to leave a commented out migration permanently in your app. And, if anyone knows why this worked (or has a better fix), please let me know!

Leave a Reply

Your email address will not be published. Required fields are marked *