Let’s say we have an e-commerce application with Order and User models.
An order belongs to a user,
and we want to add a user_id foreign key constraint on the orders table.
We would add a migration as shown below:
But if the orders table already contains foreign_key constraint on the user,
the above DB migration will raise an error.
Remove foreign key
if we try to remove a foreign_key constraint that never existed on
orders table the migration would also raise an error.
In Rails 7
To avoid above issues and to keep things consistent,
Rails team added support to pass if_exists/if_not_exists options
With this change,
the below migrations run successfully without raising any error.