0
0
RailsHow-ToBeginner · 3 min read

How to Rollback Migration in Rails: Simple Commands Explained

To rollback a migration in Rails, use the rails db:rollback command to undo the last migration. For more control, use rails db:migrate:down VERSION=timestamp to rollback a specific migration by its version number.
📐

Syntax

The main commands to rollback migrations in Rails are:

  • rails db:rollback: Reverts the last migration run.
  • rails db:rollback STEP=n: Reverts the last n migrations.
  • rails db:migrate:down VERSION=timestamp: Rolls back a specific migration by its version timestamp.

Each migration has a unique version number based on timestamp, which you can find in the migration filename.

bash
rails db:rollback
rails db:rollback STEP=3
rails db:migrate:down VERSION=20230615094500
💻

Example

This example shows how to rollback the last migration and then rollback a specific migration by version.

bash
# Run the last migration
rails db:migrate

# Rollback the last migration
rails db:rollback

# Rollback a specific migration by version
rails db:migrate:down VERSION=20230615094500
Output
== 20230615094500 CreateUsers: reverting ================================ -- drop_table(:users) -> 0.0023s == 20230615094500 CreateUsers: reverted (0.0024s) == 20230615094500 CreateUsers: reverting ================================ -- drop_table(:users) -> 0.0021s == 20230615094500 CreateUsers: reverted (0.0022s)
⚠️

Common Pitfalls

Common mistakes when rolling back migrations include:

  • Trying to rollback when no migrations have been run, which causes errors.
  • Using rails db:rollback without specifying STEP when you want to rollback multiple migrations.
  • Not checking the migration version before using rails db:migrate:down, which can rollback the wrong migration.
  • Forgetting to run rails db:migrate again after rollback if you want to reapply changes.
bash
## Wrong: rollback multiple migrations without STEP
rails db:rollback

## Right: rollback last 3 migrations
rails db:rollback STEP=3
📊

Quick Reference

CommandDescription
rails db:rollbackRollback the last migration
rails db:rollback STEP=nRollback the last n migrations
rails db:migrate:down VERSION=timestampRollback a specific migration by version
rails db:migrateRun all pending migrations

Key Takeaways

Use rails db:rollback to undo the last migration safely.
Add STEP=n to rollback multiple migrations at once.
Use rails db:migrate:down VERSION=timestamp to rollback a specific migration.
Always check migration versions before rolling back specific migrations.
Run rails db:migrate again to reapply migrations after rollback if needed.