In Ruby on Rails, how to add foreign key constraint in migration?
The error message itself showing there is a foreign key constraint error, which means you are deleting a parent table where the child table contains the Primary table identifier as a foreign key. To avoid this error, you need to delete child table records first and after that the parent table record.
Foreign keys ensure consistency between related database tables. The current database review process always encourages you to add foreign keys when creating tables that reference records from other tables. Starting with Rails version 4, Rails includes migration helpers to add foreign key constraints to database tables.
In Rails 5, adding foreign key constraints was added to have the database protect the integrity of associated data. Once a foreign key constraint is defined, your database will not allow you to remove records that are required by other tables.
Here's a gem-based solution that includes support for adding and removing foreign key constraints, doesn't fail with sqlite, and works correctly with schema.rb files:
http://github.com/matthuhiggins/foreigner
This is an update to the matthuhiggins-foreigner gem: http://github.com/sparkfly/foreigner
Features:
Future versions will include CHECK constraints for PostgreSQL, which is needed to implement multi-table inheritance.
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