Rails 7.0 Added Option To Avoid Foreign Key Migration Exceptions

July 10, 2021

Sometimes in a Ruby on Rails application, we might have a foreign key constraint defined in production database but there may not be a migration file for this.

If we add a migration file with add_foreign_key step, then that migration will run successfully against development and staging databases.
But when this migration file will be executed in production, it will raise an exception as follows.

PG::DuplicateObject: ERROR: constraint "fk_rails_########" for relation "articles" already exists


Rails 7.0 added if_exists and if_not_exists options for remove_foreign_key and add_foreign_key migration steps respectively to silence this exception.

Example:

add_foreign_key :articles, :authors, if_not_exists: true remove_foreign_key :articles, :authors, if_exists: true


When we provide if_exists or if_not_exists options, Ruby on Rails checks for a foreign key constraint exists in the database.
If it doesn't exist, it will not raise an exception.

Previously, Ruby on Rails had introduced if_exists and if_not_exists options for remove_column/add_column and remove_index/add_index migration steps as well.

Note:

If we rollback migrations with if_exists and if_not_exists options, Rails will raise an exception as these options are not reversible with change by default.

So, we need to define up and down method.

Share feedback with us at:

info@scriptday.com

© All rights reserved 2022