skip to content

Migration Files & Tasks

Rails migrations change the schema through a Ruby DSL, run and roll back through db tasks, and dump to schema.rb or structure.sql. Interviewers probe safe changes on large live tables.

part ofRuby on Railsread it →
on this pageshow

explore

questions

26

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 a Rails app, what is db/schema.rb, what writes it, and why do teams commit it instead of editing it by hand?

level: juniorimportance: must knowfreq 60%

basics

~20 s

db/schema.rb is Active Record's Ruby snapshot of the current database structure, rewritten from the live database after db:migrate and db:rollback. Teams commit it because new and test databases are built from it, and hand edits are overwritten at the next dump.

open as a page

In Rails, what is db/seeds.rb for, how do you load it, and why write it with find_or_create_by! instead of create!?

level: juniorimportance: must knowfreq 55%

basics

~20 s

db/seeds.rb is a Ruby file that creates the rows an app needs, such as countries and default plans, and bin/rails db:seed runs it. It may run many times, so find_or_create_by! makes reruns find existing rows instead of duplicating them.

open as a page

In a Rails 8.1 migration, how do you create a shipments table that belongs to couriers, and what does t.references :courier add?

level: juniorimportance: must knowfreq 75%

basics

~20 s

Call create_table :shipments in the change method. Inside it, t.references :courier adds a bigint courier_id column and an index on it; a real foreign key constraint appears only with foreign_key: true, and NOT NULL only with null: false.

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 Rails online-auction app, a trigger on bids created with execute is missing from db/schema.rb; why, and how does schema_format :sql fix it?

level: middleimportance: must knowfreq 50%

basics

~20 s

db/schema.rb holds only what Active Record's Ruby DSL can express, so a trigger made with execute is silently left out and every database built from the file lacks it. With schema_format :sql, Rails writes db/structure.sql with the database's own dump tool, trigger included.

open as a page

In a Rails migration, which calls can a change method reverse automatically, and when must you write up and down instead?

level: middleimportance: must knowfreq 65%

basics

~20 s

On rollback Rails replays change through a command recorder and inverts each call: create_table, add_column, add_index, add_reference, add_foreign_key and rename_column invert cleanly. change_column, execute and under-specified removals raise ActiveRecord::IrreversibleMigration, so those need up and down.

open as a page

In a Rails app on PostgreSQL, how do you add an index to a 50-million-row events table without blocking writes, and what does that cost the migration?

level: seniorimportance: must knowfreq 58%

basics

~20 s

Call add_index :events, [:account_id, :occurred_at], algorithm: :concurrently in a migration that declares disable_ddl_transaction!. The build no longer blocks writes, but the migration loses its transaction, so a failure leaves partial work and no schema_migrations row.

open as a page

In a Rails 8.1 app, how do you drop the legacy_payload column from a busy events table without errors from servers still running the old code?

level: seniorimportance: must knowfreq 55%

basics

~10 s

Ship it in two releases: first add self.ignored_columns += ["legacy_payload"] to Event and remove every use, then deploy a migration with safety_assured { remove_column :events, :legacy_payload, :jsonb }, and finally delete the ignore line.

open as a page

In a Rails app using the strong_migrations gem, what happens when a migration runs a risky operation, and what is safety_assured for?

level: juniorimportance: should knowfreq 38%

basics

~20 s

strong_migrations checks each schema call a Rails migration makes and stops risky ones, such as blocking index builds or column drops, with StrongMigrations::UnsafeMigration and a safer recipe. safety_assured { ... } skips the check for a step you made safe.

open as a page

In Rails, why does naming a migration AddTrackingNumberToShipments make bin/rails generate migration write the add_column call for you?

level: juniorimportance: should knowfreq 50%

basics

~10 s

The migration generator reads the name: add_...to<table> fills change with add_column calls on that table, remove_...from<table> with remove_column calls, and create_<table> with a create_table block; any other name leaves change empty.

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

Why should a Rails migration that adds a column to the busy events table not also backfill it with Event.update_all?

level: middleimportance: should knowfreq 50%

basics

~20 s

Rails runs the migration in one transaction, so add_column's lock on events lasts until the UPDATE over every row commits, blocking traffic for the whole backfill. Add the column in one migration; backfill in batches outside a transaction.

open as a page

With strong_migrations in a Rails app, where do the 10-second lock timeout and 1-hour statement timeout come from, and why does a migration need them?

level: middleimportance: should knowfreq 28%

basics

~20 s

They come from config/initializers/strong_migrations.rb, which bin/rails generate strong_migrations:install writes; the gem itself sets no timeout. The short lock timeout stops a waiting ALTER from queueing all traffic behind it, and the long statement timeout lets index builds finish.

open as a page

In Rails 8.1, why build a new database with db:schema:load instead of replaying every migration, and what does loading record?

level: middleimportance: should knowfreq 45%

basics

~20 s

Loading the schema file is one fast pass that cannot trip over old migrations whose models or gems have since changed. It recreates every table, then marks the file's version and every older migration as applied, and stores the environment and schema checksum.

open as a page

In Rails, how do timestamped migration versions behave when two branches each add a migration, and how do you resolve the db/schema.rb conflict?

level: middleimportance: should knowfreq 40%

basics

~20 s

Each migration's version is a UTC timestamp, so two branches rarely collide, but both rewrite db/schema.rb's version line and often the same tables. Resolve by migrating the merged code and committing the regenerated file, never by hand-picking lines.

open as a page

In a Rails 8.1 app, how do you seed demo learners only in development while countries and plans load in every environment, including production?

level: middleimportance: should knowfreq 35%

basics

~20 s

Rails loads the same db/seeds.rb in every environment, so the file must branch itself: reference data such as countries and plans at the top, demo learners behind Rails.env.development? or in a db/seeds/development.rb that seeds.rb loads only there.

open as a page

What does bin/rails db:seed:replant do in Rails 8.1, and what stops it from wiping a production database?

level: middleimportance: should knowfreq 25%

basics

~10 s

db:seed:replant empties every table of the current environment's databases, except Rails' own schema_migrations and ar_internal_metadata, and then runs db/seeds.rb. It is a protected task: against a database last used as production it raises ActiveRecord::ProtectedEnvironmentError.

open as a page

In a Rails migration, what do add_foreign_key and add_check_constraint create, and what must you pass so removing them stays reversible?

level: middleimportance: should knowfreq 40%

basics

~10 s

add_foreign_key adds a FOREIGN KEY constraint named fk_rails_<hash>, add_check_constraint a CHECK constraint named chk_rails_<hash>. Both invert on rollback; removing them is reversible only if remove_foreign_key names the target table and remove_check_constraint repeats the expression.

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

In a Rails migration on PostgreSQL, why add a foreign key from events to accounts with validate: false and validate it in a second migration?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Adding a validated foreign key makes PostgreSQL check all 50 million existing events while writes are blocked. With validate: false only new writes are checked, and validate_foreign_key later scans the old rows under a lock that lets writes continue.

open as a page

A Rails 8.1 release adds a Family plan that production must have; does it belong in db/seeds.rb, a data migration, or a one-off task?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Usually both: a deploy runs migrations, not seeds, so a data migration adds the plan to existing databases, and db/seeds.rb adds it to new ones, which since Rails 8.0 load the schema instead of replaying migrations.

open as a page

A Rails 8.1 courier app shipped AddLegacyBarcodeToShipments to production; how do you undo it with a new migration using revert, and where do reversible and up_only fit?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Write a new migration whose change calls revert AddLegacyBarcodeToShipments after require_relative of that file; db:migrate runs the old migration inverted. reversible lets one step pick SQL per direction, and up_only runs a step only on the way up.

open as a page

In a multi-database Rails 8.1 app, what does the seeds: key in config/database.yml control, and what is its default?

level: middleimportance: nice to knowfreq 12%

basics

~10 s

seeds: decides whether bin/rails db:prepare runs db/seeds.rb after it sets up that database. It defaults to true for the primary database and false for the others, such as the cache, queue and cable databases.

open as a page

An online-auction Rails app has 900 migration files going back years; how do you prune old migrations safely, and what changes afterwards?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

Delete migration files only after every environment has run them and the committed schema file is correct, because new databases load that file. Old schema_migrations rows stay and show as NO FILE, and rollbacks can no longer reach the pruned range.

open as a page