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
DROPcontact_id
So how do I remove this foreign key constraint in the Rails migration too?
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.
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.
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.
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.
Try...
def change
remove_reference :addresses, :contact, index: true, foreign_key: true
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With