0
0
Ruby on Railsframework~3 mins

Why Running and rolling back migrations in Ruby on Rails? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could fix database mistakes with a single command instead of hours of manual work?

The Scenario

Imagine you have to add a new column to your database table by writing raw SQL every time you update your app.

Then, you realize you made a mistake and need to undo that change manually.

The Problem

Manually changing the database is risky and slow.

You might forget the exact commands to undo changes, causing errors or data loss.

It's hard to keep track of what changes were made and when.

The Solution

Rails migrations let you write simple Ruby code to change your database structure.

You can easily run these changes or roll them back with simple commands.

This keeps your database in sync with your app code safely and clearly.

Before vs After
Before
ALTER TABLE users ADD COLUMN age INTEGER;
-- To undo:
ALTER TABLE users DROP COLUMN age;
After
rails generate migration AddAgeToUsers age:integer
rails db:migrate
rails db:rollback
What It Enables

You can safely evolve your database step-by-step as your app grows, with full control to undo mistakes.

Real Life Example

When adding a new feature that needs extra data, you create a migration to add columns instead of manually editing the database.

If the feature isn't ready, you roll back the migration to keep the database clean.

Key Takeaways

Manual database changes are error-prone and hard to track.

Migrations automate applying and undoing database changes safely.

This keeps your app and database in sync and easy to manage.