Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a foreign key column using a Rails migration

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?

like image 325
Daniel Viglione Avatar asked Aug 22 '18 23:08

Daniel Viglione


People also ask

Can you edit a migration file rails?

If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run rake db:migrate.

How do you delete a column in rails?

remove_column :table_name, :column_name, :type Removes column, also adds column back if migration is rollbacked. Note: If you skip the data_type, the migration will remove the column successfully but if you rollback the migration it will throw an error.

What is Add_index in rails migration?

add_index(table_name, column_name, options = {}) public. Adds a new index to the table. column_name can be a single Symbol, or an Array of Symbols. The index will be named after the table and the column name(s), unless you pass :name as an option.

What can rails migration do?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.


1 Answers

Try...

def change
  remove_reference :addresses, :contact, index: true, foreign_key: true
end
like image 190
Mark Merritt Avatar answered Oct 19 '22 23:10

Mark Merritt