Rails 7.1 Adds Adapter Option To Disallow Foreign Keys.

In Rails, adapters allow us to connect to different databases, while foreign keys are constraints that ensure the values in one table match valid records in another table. This helps to maintain data integrity.

If there is a need to disallow foreign keys temporarily, such as during data imports, we have to write migrations to drop foreign keys from each table individually.

This process is cumbersome and time consuming, especially in applications with multiple tables and relationships.

Before

We need to manually create migrations to drop foreign keys for each table, making it a labor-intensive task.

Once data import completes, we have to write additional migrations to re-add the foreign keys, further complicating the process.

After

Rails 7.1 introduces adapter option to disallow foreign keys.

By adding foreign_keys: false option to database.yml, we can skip the foreign key constraints usage even if the underlying database supports them.

development:
  <<: *default
  database: db/development.sqlite3
  foreign_keys: false

The new foreign_keys option allows us to disable foreign key constraints for the entire application through the database configuration, eliminating the need for multiple migrations.

Need help on your Ruby on Rails or React project?

Join Our Newsletter