Ruby-on-rails – Remove a foreign key column using a Rails migration

ruby-on-rails

I am simply trying to remove a foreign key column from a table. I have this in migration:

def change
  remove_column :addresses, :contact_id
end  

However, I get the following error:

Mysql2::Error: Cannot drop index 'index_addresses_on_contact_id':
needed in a foreign key constraint: ALTER TABLE addresses DROP
contact_id

So how do I remove this foreign key constraint in the Rails migration too?

Best Answer

Try...

def change
  remove_reference :addresses, :contact, index: true, foreign_key: true
end