skip to content

Migrate & Rollback Commands

The db tasks apply, roll back and report migrations against the schema_migrations table, and db:prepare sets up or migrates in one call. Interviewers ask what each task really runs.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

In Rails, what do bin/rails db:migrate and bin/rails db:rollback STEP=2 do, and how does each decide which migrations to run?

level: juniorimportance: must knowfreq 75%

answer

  1. one row per applied version
  2. pending means file without a row
  3. ascending order, one transaction each
  4. rollback walks back by version number
  5. schema file dumped afterwards

basics

~20 s

db:migrate runs every migration file whose version has no row in the schema_migrations table, oldest first, inserting a row after each. db:rollback STEP=2 runs the down direction of the two highest-numbered applied migrations and deletes their rows.

solid answer

~40 s

Rails tracks applied migrations in the `schema_migrations` table: one `version` string per migration that has run. `bin/rails db:migrate` compares the files in `db/migrate` with those rows and runs every **pending** one in ascending version order, each `up` (or `change`) wrapped in its own transaction on databases with transactional DDL, inserting the version row inside the same transaction. `bin/rails db:rollback` defaults to `STEP=1`; `STEP=2` starts from the highest applied version, steps back two migrations in version order, runs their `down` (or `change` reversed) newest first and deletes their rows. Both tasks then rewrite `db/schema.rb` unless `config.active_record.dump_schema_after_migration` is false, as it is in the generated `production.rb`. If a migration fails, it and the ones after it are cancelled; earlier ones in the run stay applied.

code

bash · 4 lines
bash
bin/rails db:migrate
bin/rails db:rollback
bin/rails db:rollback STEP=2
bin/rails db:migrate:status

go deeper

for a junior

Know that db:migrate runs pending migrations and db:rollback undoes the last one, and that schema_migrations records which versions have run.

for a middle

Explain pending as files without rows, the per-migration transaction, what STEP counts, and why rollback goes by version number rather than run order.

for a senior

Check status before rolling back shared databases, know what a failed run leaves behind with and without transactional DDL, and keep schema_migrations untouched by hand.

for a principal

Decide when rollbacks are an accepted tool on shared environments and when the team ships a new migration instead.

## The table that drives both tasks Every Rails database that has been migrated contains a table called `schema_migrations` with one column, `version`. Each row is the timestamp prefix of a migration file that has run against **this** database, for example `20261002143000` for `db/migrate/20261002143000_add_allergy_notes_to_patients.rb`. Nothing else about the migration is stored: not its name, not when it ran, not what it did. The table is created automatically, together with `ar_internal_metadata`, the first time Rails migrates the database. Both `db:migrate` and `db:rollback` work by comparing that table with the files in `db/migrate`. ## db:migrate In a dental-practice app, `bin/rails db:migrate`: 1. Lists the migration files and reads their versions from the file names. 2. Treats every file whose version has **no row** as pending. Order of merging does not matter: an older-stamped file that arrived late is still pending. 3. Runs the pending migrations in ascending version order. Each runs its `change` (or `up`) method. 4. Wraps each migration in its own transaction when the adapter supports transactional DDL (PostgreSQL and SQLite do; MySQL does not) and the migration has not opted out with `disable_ddl_transaction!`, and inserts the version row inside that transaction. 5. Dumps the schema file afterwards, unless `config.active_record.dump_schema_after_migration` is false, which the generated `config/environments/production.rb` sets. Running it again with nothing pending does nothing. If the third of five pending migrations raises, Rails reports that it and all later migrations were cancelled. The first two stay applied, and with transactional DDL the third leaves no trace. ## Reading what it prints Each migration announces itself and times every schema call: ``` == 20261002143000 AddAllergyNotesToPatients: migrating ======================== -- add_column(:patients, :allergy_notes, :text) -> 0.0021s == 20261002143000 AddAllergyNotesToPatients: migrated (0.0034s) =============== ``` Rolling back prints the same frame with `reverting` and `reverted`. `VERBOSE=false` silences the output. The log is the quickest way to see which migration a failed run stopped in, because the last `migrating` line without a matching `migrated` is the culprit. ## db:rollback STEP=n `bin/rails db:rollback` undoes migrations from the top: - With no `STEP`, it undoes one: the migration with the **highest applied version**. - `STEP=2` starts at that highest version, steps back two places through the migration files in version order, and runs the down direction for the applied ones in that range, newest first. - Each down runs `down`, or `change` in reverse, then deletes the version row in the same transaction. - The schema file is dumped again afterwards. Note what "last" means here: **highest version number**, not "most recently executed". If a late-merged migration with an older timestamp ran yesterday, `db:rollback` still starts from the newest-stamped one. `db:rollback` does not accept a target version. `bin/rails db:rollback VERSION=...` raises an error that points you to `db:migrate:down`, the task for one specific migration. ## A staging example On a staging copy of the dental-practice app, the last two migrations added `appointments.reminder_sent_at` and an index on `patients.last_visit_on`. Rolling them back: ```bash bin/rails db:migrate:status # confirm which two are on top RAILS_ENV=staging bin/rails db:rollback STEP=2 bin/rails db:migrate:status # both now show "down" ``` After the rollback, both rows are gone from `schema_migrations`, so the next `db:migrate` treats those two files as pending again and reapplies them. ## What these tasks do not do | Belief | What actually happens | |---|---| | `db:migrate` re-runs every file | only files without a version row run | | The version list lives in `db/schema.rb` | the database's `schema_migrations` table holds it; the schema file shows only the highest version | | Rollback undoes the most recently executed migrations | it goes by version number | | A failed migration rolls back the whole run | only the failing migration's transaction is undone | | Rollback restores deleted data | it runs the `down` code; data dropped by `up` is gone | ## Habits that keep this safe - Run `bin/rails db:migrate:status` before rolling back on any shared database, so you know which two migrations `STEP=2` will hit. - Never delete rows from `schema_migrations` by hand to "skip" a migration; the next migrate or rollback then disagrees with the real schema. - Commit the regenerated `db/schema.rb` together with the migration that changed it.

  • The migration you roll back added a column that now holds data. What happens to that data?
    Rollback runs the migration's down direction, so the column is removed together with its values. Rolling forward again recreates the column empty. `db:rollback` restores structure by running code, not data; if the values matter, copy them somewhere first or write a new migration instead of rolling back.
  • What happens to the schema_migrations rows if a migration fails halfway through db:migrate?
    Each migration runs in its own transaction on adapters with transactional DDL, and its version row is inserted inside that transaction. The failing migration's changes and row are rolled back, migrations after it do not run, and migrations before it keep their rows. On MySQL there is no DDL transaction, so a half-applied migration can leave schema changes without a row.

  • db:rollback STEP=2 undoes the two migrations that ran most recently, whatever their versions
  • db:migrate runs every migration file again on each call
  • db:rollback VERSION=20261001090000 rolls back to that version
  • Rails reads the list of applied migrations from db/schema.rb
  • If the third of five migrations fails, Rails undoes the first two as well
open as a page

In Rails 8.1, what do db:create, db:setup, db:reset and db:prepare each do, and which of them replays your migrations?

level: middleimportance: must knowfreq 55%

basics

~20 s

db:create makes empty databases; db:setup creates, loads the schema file and seeds; db:reset drops then runs setup; db:prepare sets up a missing database or runs pending migrations on an existing one. None replays all migrations; db:migrate:reset does.

open as a page

In a new Rails 8.1 app whose production database.yml lists primary, cache, queue and cable, how do db:migrate, db:migrate:primary and db:rollback behave?

level: middleimportance: should knowfreq 35%

basics

~10 s

Rails generates namespaced tasks per database. db:migrate migrates all four, each against its own migrations_paths and schema_migrations; db:migrate:primary only the primary. Unnamed db:rollback raises in a multi-database environment, so you run db:rollback:primary.

open as a page

In Rails, how do db:migrate VERSION=, db:migrate:up, db:migrate:down, db:migrate:redo and db:migrate:status differ when you work on one migration?

level: middleimportance: should knowfreq 45%

basics

~20 s

db:migrate VERSION=x moves the database to x, rolling back everything above it or migrating up to it. db:migrate:up and :down run one migration's single direction, redo rolls back and re-runs, and status lists each version as up or down.

open as a page

On a staging database restored from a production dump, why does bin/rails db:reset refuse to run, and what does ar_internal_metadata have to do with it?

level: seniorimportance: should knowfreq 30%

basics

~10 s

ar_internal_metadata stores the environment that last migrated the database; the dump says production. Destructive tasks check it first and raise ActiveRecord::ProtectedEnvironmentError for production, so db:reset stops until db:environment:set records staging.

open as a page