Guides

Rails migrations cheat sheet: generator syntax, column types and db commands (free PDF)

Guides · · Published 2026-12-04

Migrations are the part of Rails most developers use every week and still look up every time: was it AddUserRefToPosts or AddUserToPosts, which methods can change reverse on its own, what is the difference between db:reset and db:migrate:reset? This page gathers the answers on one sheet. Download the two-page PDF to keep next to your keyboard, or copy the text version below. Everything on it was checked on 4 December 2026 against the official Active Record Migrations guide and the API documentation for Rails 8.1, the current release series.

Download: Rails migrations cheat sheet (PDF, A4, 2 pages). Free to print and share within your team. The same content is in plain text at the end of this page.

What the sheet covers

The sheet is built around the order in which you meet migrations in practice. First you generate a file, so the top of page one lists the generator's naming conventions and the field syntax it understands. Then you edit the file, so the next blocks give the native column types, the column options and the methods that change knows how to reverse. Page two is about running migrations: the db: commands grouped by what they do, how the schema file fits in, and a short list of the mistakes that most often break a deploy. Each section below explains one block of the sheet in more detail.

The examples use bin/rails, as the guides do. Generated migration classes inherit from ActiveRecord::Migration[8.1] in a Rails 8.1 app; the number in brackets records the Rails version the migration was written for, so older files in the same app keep their own number and keep behaving as they did. If you are still on 8.0, our guide to upgrading from Rails 8.0 to 8.1 explains why it is worth moving now.

Generating a migration: names that do the work

bin/rails generate migration reads the name you give it. When the name follows one of a few patterns, it writes the body of the migration for you; otherwise it creates an empty change method. The file name starts with a UTC timestamp, which is also the version Rails stores once the migration has run.

Name patternExampleWhat the generator writes
CreateXxxCreateProducts name:stringcreate_table :products with the listed columns and t.timestamps
AddXxxToYyyAddPartNumberToProducts part_number:stringadd_column :products, :part_number, :string
RemoveXxxFromYyyRemovePartNumberFromProducts part_number:stringremove_column with the type, so it stays reversible
AddXxxRefToYyyAddUserRefToProducts user:referencesadd_reference :products, :user, null: false, foreign_key: true
Name containing JoinTableCreateJoinTableUserProduct user productcreate_join_table :users, :products with commented index lines

After the name come the fields, written name:type. A few suffixes save a manual edit:

One thing the command line cannot do is set a default value: the guide states plainly that default cannot be passed when generating. Add it in the file. And remember that bin/rails generate model writes a CreateXxx migration too, so you rarely need both commands for a new table.

Column types and options

The API documentation for add_column lists the native, database-agnostic types: :primary_key, :string, :text, :integer, :bigint, :float, :decimal, :numeric, :datetime, :time, :date, :binary, :blob and :boolean. You can use any other type your database supports, such as :jsonb on PostgreSQL, at the cost of tying the migration to that database. In create_table blocks, t.references and t.timestamps are shortcuts for the foreign key column and the created_at/updated_at pair.

Options are passed as a hash after the type:

For money, use :decimal with an explicit precision and scale rather than :float, which stores approximations. Gems that need extra columns, such as a deleted_at timestamp for the libraries in our guide to soft deletes, usually ship their own generator; read the migration it writes before you run it.

Writing change so it can be rolled back

change is the default way to write a migration: you describe the forward step and Rails works out the reverse. That only works for methods whose reverse it can compute. According to the guide, change supports, among others, create_table, create_join_table, add_column, add_index, add_reference, add_foreign_key, add_timestamps, add_check_constraint, change_column_null, rename_column, rename_index, rename_table, enable_extension and disable_extension.

A second group is reversible only if you give Rails the information it would otherwise lose:

change_column is not reversible at all. When you need it, wrap it in reversible do |direction| … end with direction.up and direction.down blocks, or write separate up and down methods. If a step genuinely cannot be undone, for example because it destroys data, raise ActiveRecord::IrreversibleMigration in down so that a rollback stops with a clear message instead of half-working.

Two further details are easy to miss. change_column_default only affects future records, while change_column_null :products, :name, false applies to existing rows as well, so every existing row must already have a value. Fill the column first, in a separate step, then add the constraint.

Indexes, references and foreign keys

add_reference :products, :user, foreign_key: true adds the user_id column, an index on it and a database-level foreign key in one call. add_index :products, :part_number, unique: true adds a unique index; pass an array of columns for a composite index. On PostgreSQL, algorithm: :concurrently builds the index without locking writes to the table, but it cannot run inside a transaction, so the migration also needs disable_ddl_transaction! at class level. Without the transaction, a failure halfway through leaves the earlier steps applied, so keep such a migration to that single operation.

Unique indexes matter more than they look. A validates :email, uniqueness: true in the model does not stop two requests from inserting the same value at the same moment; the unique index does. The same reasoning applies to the tenant keys discussed in our guide to multi-tenancy in Rails.

Running migrations: the db: commands

CommandWhat it does
bin/rails db:migrateRuns every pending migration in timestamp order, then dumps the schema file.
bin/rails db:migrate VERSION=20261204120000Migrates up or down until the database is at that version.
bin/rails db:rollback STEP=3Reverts the last three migrations (one without STEP).
bin/rails db:migrate:redo STEP=3Rolls back and re-runs the last migrations: useful while you are still editing a local one.
bin/rails db:migrate:statusLists every migration as up or down; a deleted file that once ran shows as NO FILE.
bin/rails db:migrate:up VERSION=… / :downRuns one specific migration in one direction, and does nothing if it is already in that state.
bin/rails db:migrate RAILS_ENV=testRuns migrations against another environment.
bin/rails db:setupCreates the database, loads the schema and runs the seeds.
bin/rails db:prepareLike db:setup, but idempotent: safe to call on every deploy or container start.
bin/rails db:resetDrops and recreates the database from the current schema file. It does not replay migrations.
bin/rails db:migrate:resetDrops the database and replays every migration from the beginning.
bin/rails db:schema:loadLoads the schema file into an empty database: faster and safer than replaying years of migrations.
bin/rails db:seed / db:seed:replantRuns db/seeds.rb; replant empties the tables first.

The difference between the two resets is the one that bites. db:reset trusts db/schema.rb; db:migrate:reset trusts the migration files. If someone edited, reordered or deleted old migrations, the two can produce different databases, which the guide calls schema drift.

The schema file

Every db:migrate also runs db:schema:dump, which rewrites db/schema.rb to match the database. The format is set by config.active_record.schema_format: :ruby by default, or :sql to write db/structure.sql instead, which you need for database features the Ruby format cannot express, such as triggers or composite foreign keys. The guide strongly recommends committing the schema file. When two branches both change it and Git reports a conflict, do not merge it by hand: run bin/rails db:migrate and let Rails regenerate it.

A Rails upgrade can rewrite the schema file without any migration being added, for instance by reordering columns. Review that diff on its own commit so that it does not hide a real change, as we suggest in our 8.1 upgrade guide.

Mistakes that break deploys

Text version of the cheat sheet

The same content as the PDF, ready to paste into a team wiki or a README:

RAILS MIGRATIONS CHEAT SHEET (Rails 8.1) - Gemfile Review, railsplugins.org
Checked against guides.rubyonrails.org/active_record_migrations.html, 4 Dec 2026

GENERATE
bin/rails generate migration CreateProducts name:string price:decimal
bin/rails generate migration AddPartNumberToProducts part_number:string:index
bin/rails generate migration RemovePartNumberFromProducts part_number:string
bin/rails generate migration AddUserRefToProducts user:references
bin/rails generate migration CreateJoinTableUserProduct user product
Field suffixes: name:type:index   'price:decimal{5,2}'
                supplier:references{polymorphic}   email:string!  (null: false)
Defaults cannot be set from the command line: edit the file.

NATIVE COLUMN TYPES
:primary_key :string :text :integer :bigint :float :decimal :numeric
:datetime :time :date :binary :blob :boolean
Options: null: false | default: | limit: | precision: | scale: | comment:
Indexes: index: true / index: { unique: true } inside create_table,
         add_index :table, :column, unique: true elsewhere

REVERSIBLE IN change
create_table create_join_table add_column add_index add_reference
add_foreign_key add_timestamps add_check_constraint change_column_null
rename_column rename_index rename_table enable_extension disable_extension
Reversible only with extra info:
  remove_column(s)        -> original type and options
  change_column_default   -> from: / to:
  drop_table              -> options and block
  remove_index / _reference / _foreign_key / _timestamps -> original options
Not reversible: change_column -> use reversible do |dir| or up/down
Truly irreversible: raise ActiveRecord::IrreversibleMigration in down

RUN
bin/rails db:migrate                      run pending, then dump schema
bin/rails db:migrate VERSION=2026...      go to a version
bin/rails db:rollback STEP=3              undo last 3
bin/rails db:migrate:redo STEP=3          undo and redo last 3
bin/rails db:migrate:status               up / down / NO FILE
bin/rails db:migrate:up VERSION=...       one migration, one direction
bin/rails db:migrate RAILS_ENV=test       other environment
bin/rails db:prepare                      idempotent setup (deploys)
bin/rails db:reset                        drop + load schema file + seeds
bin/rails db:migrate:reset                drop + replay all migrations
bin/rails db:schema:load                  load schema into empty database
bin/rails db:seed:replant                 empty tables, re-run seeds

SCHEMA FILE
db/schema.rb (default, :ruby) or db/structure.sql (:sql)
Commit it. On a merge conflict: bin/rails db:migrate to regenerate.

BEFORE YOU PUSH
[ ] Never edit a migration that ran on another machine
[ ] No application models inside migrations
[ ] Data changes outside schema migrations
[ ] NOT NULL on a full table: add nullable, backfill, then constrain
[ ] Rollback tested locally (db:migrate:redo)
[ ] Big PostgreSQL index: algorithm: :concurrently + disable_ddl_transaction!

For the full reference, keep the SchemaStatements API page open alongside the guide: it documents every option of every method, including the adapter-specific ones that a two-page sheet leaves out.

Sheet and page compiled by Gemfile Review, 4 December 2026. We will update both when a new Rails release changes the generator or the commands.