Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Support for foreign key constraint in Rails

In Ruby on Rails, how to add foreign key constraint in migration?

like image 945
Lakshmi Avatar asked Nov 26 '08 10:11

Lakshmi


People also ask

How do I fix foreign key constraint failure?

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.

Do you need foreign keys in Rails?

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.

How does foreign key work in Rails?

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.


2 Answers

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

like image 142
Jason Wadsworth Avatar answered Oct 12 '22 19:10

Jason Wadsworth


This is an update to the matthuhiggins-foreigner gem: http://github.com/sparkfly/foreigner

Features:

  • rspec coverage, tested against PostgreSQL 8.3.9 and MySQL 5.0.90
  • Migration support
  • schema.rb support

Future versions will include CHECK constraints for PostgreSQL, which is needed to implement multi-table inheritance.

like image 23
Ho-Sheng Hsiao Avatar answered Oct 12 '22 20:10

Ho-Sheng Hsiao