Rails 7.1 adds adapter option to disallow foreign keys

Aditya Bhutani

By Aditya Bhutani

on February 21, 2023

This blog is part of our  Rails 7 series.

There are times when an application can choose not to use foreign keys. Data transfer between services is a tricky thing. When we are importing the data we need to import data in the right order if "foreign keys" are enabled. In such cases one might want to not enforce "foreign keys" and load the data and then add "foreign keys" constraint back.

Situations like this can be handled using migrations. Using migrations we can disable "foreign keys". However this would mean writing migrations for all the tables and removing all "foreign keys". This could be cumbersome.

1def change
2  create_table :authors do |t|
3    t.string :name
4    t.timestamps
5  end
7  create_table :books do |t|
8    t.belongs_to :author, foreign_key: false
9    t.datetime :published_at
10    t.timestamps
11  end

Rails 7.1 adds option to database.yml that enables skipping foreign key constraints usage even if the underlying database supports them and solves the above issue of writing migrations to disable foreign keys for all the tables.

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

Please check out this pull request for more details.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.