Rake DB:Migrate Error due to Foreign Key

I had so many junk/test records in my Rails project and thought “hey… rake DB:migrate is a quick way to wipe those records.”

I ran ‘rake db:migrate VERSION=0′ and MySQL was not too happy with me.

Here is the error:

rake aborted!
Mysql::Error: Error on rename of ‘./<database name>/#sql-bb3b_3′ to ‘./<database name>/contexts’ (errno: 150): ALTER TABLE `contexts` DROP `user_id`

Again… Google is my best friend to find these kind of errors. :)
The problem is caused by database foreign key.

If your migration has the following line:

class MigrationName < ActiveRecord::Migration
def self.up
  .
  .
  execute “alter table <table name> add constraint <foreign key name> foreign key (<column name>) references …”
end

The solution is to drop the foreign key first before removing the column:

def self.down
  execute “alter table <table name> drop foreign key <foreign key name>”
  remove_column …
end

Leave a Reply