Rails 7.1 adds adapter option to disallow foreign keys

Aditya Bhutani

Aditya Bhutani

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.

def change
  create_table :authors do |t|
    t.string :name
    t.timestamps
  end

  create_table :books do |t|
    t.belongs_to :author, foreign_key: false
    t.datetime :published_at
    t.timestamps
  end
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.

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

Please check out this pull request for more details.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.