Migrations help you change your database step-by-step. Running migrations applies changes. Rolling back undoes them if needed.
0
0
Running and rolling back migrations in Ruby on Rails
Introduction
When you add a new table or column to your database
When you fix a mistake in a previous database change
When you want to test changes without permanently applying them
When you need to reset your database to a previous state
When collaborating with others and syncing database changes
Syntax
Ruby on Rails
rails db:migrate rails db:rollback STEP=n
rails db:migrate runs all pending migrations in order.
rails db:rollback undoes the last migration by default. Use STEP=n to undo multiple steps.
Examples
This runs all new migrations that have not been applied yet.
Ruby on Rails
rails db:migrate
This rolls back the last migration that was run.
Ruby on Rails
rails db:rollback
This rolls back the last 3 migrations in reverse order.
Ruby on Rails
rails db:rollback STEP=3Sample Program
First, we run all pending migrations to update the database. Then, we undo the last migration. Finally, we undo the last two migrations to go back further.
Ruby on Rails
# Run migrations rails db:migrate # Rollback last migration rails db:rollback # Rollback last 2 migrations rails db:rollback STEP=2
OutputSuccess
Important Notes
Always check your migration files before running or rolling back to avoid data loss.
Rolling back migrations only affects the database schema, not your application code.
You can use rails db:migrate:status to see which migrations have run.
Summary
Running migrations applies database changes step-by-step.
Rolling back undoes migrations to fix or test changes.
Use STEP=n with rollback to undo multiple migrations at once.