I am a seasoned developer with over 9 years of experience in Ruby on Rails and Golang. My passion lies in tackling complex data structures and algorithm problems, always pushing myself to learn and grow. In my downtime, I find solace in the pages of books and the soothing sounds of a guitar. But I'm not just a one-trick pony! I love to stay active and challenge myself in other ways too. Whether it's on the football pitch, cricket field, table tennis table, or badminton court, I'm always up for some fun activities.
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.