Rails migrations cheat sheet: generator syntax, column types and db commands (free PDF)
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 pattern | Example | What the generator writes |
|---|---|---|
CreateXxx | CreateProducts name:string | create_table :products with the listed columns and t.timestamps |
AddXxxToYyy | AddPartNumberToProducts part_number:string | add_column :products, :part_number, :string |
RemoveXxxFromYyy | RemovePartNumberFromProducts part_number:string | remove_column with the type, so it stays reversible |
AddXxxRefToYyy | AddUserRefToProducts user:references | add_reference :products, :user, null: false, foreign_key: true |
Name containing JoinTable | CreateJoinTableUserProduct user product | create_join_table :users, :products with commented index lines |
After the name come the fields, written name:type. A few suffixes save a manual edit:
part_number:string:indexadds anadd_indexline for the new column.'price:decimal{5,2}'sets precision and scale; quote it so your shell does not expand the braces.supplier:references{polymorphic}creates the_idand_typecolumns of a polymorphic reference.email:string!addsnull: false. The exclamation mark is documented in the current guide; on an older app, checkbin/rails generate migration --helpbefore relying on it.
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:
null: falseforbids NULL;default:sets a default (usenilfor NULL). Depending on the database, existing rows may not receive the default.limit:is a number of characters for a string column and a number of bytes for text, binary and integer columns.precision:andscale:apply to decimal and numeric columns (precision also to datetime and time).comment:stores a description in the database; the guide notes that only the MySQL and PostgreSQL adapters support comments.index: trueorindex: { unique: true }works insidecreate_table, but not withadd_columnorchange_column: there, add the index separately withadd_index.
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:
remove_columnandremove_columns: pass the original type and options.change_column_default,change_column_comment,change_table_comment: passfrom:andto:, as inchange_column_default :products, :approved, from: true, to: false.drop_table: pass the table options and the block that created it.remove_index,remove_reference,remove_foreign_key,remove_timestamps,remove_check_constraint: pass the original columns, options or expression.
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
| Command | What it does |
|---|---|
bin/rails db:migrate | Runs every pending migration in timestamp order, then dumps the schema file. |
bin/rails db:migrate VERSION=20261204120000 | Migrates up or down until the database is at that version. |
bin/rails db:rollback STEP=3 | Reverts the last three migrations (one without STEP). |
bin/rails db:migrate:redo STEP=3 | Rolls back and re-runs the last migrations: useful while you are still editing a local one. |
bin/rails db:migrate:status | Lists every migration as up or down; a deleted file that once ran shows as NO FILE. |
bin/rails db:migrate:up VERSION=… / :down | Runs one specific migration in one direction, and does nothing if it is already in that state. |
bin/rails db:migrate RAILS_ENV=test | Runs migrations against another environment. |
bin/rails db:setup | Creates the database, loads the schema and runs the seeds. |
bin/rails db:prepare | Like db:setup, but idempotent: safe to call on every deploy or container start. |
bin/rails db:reset | Drops and recreates the database from the current schema file. It does not replay migrations. |
bin/rails db:migrate:reset | Drops the database and replays every migration from the beginning. |
bin/rails db:schema:load | Loads the schema file into an empty database: faster and safer than replaying years of migrations. |
bin/rails db:seed / db:seed:replant | Runs 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
- Editing a migration that already ran elsewhere. Rails records the version in the
schema_migrationstable and will never run that file again on a machine where it has run. Write a new migration instead; only edit migrations that exist on your own machine, and usedb:migrate:redowhile you do. - Using application models inside migrations. The model code changes over time, the migration does not. A migration that calls
Product.where(…)may fail a year later. Use SQL, or a minimal model class defined inside the migration. - Mixing data changes into schema migrations. The guide advises against data migrations in migration files: they are hard to roll back and can lock tables for a long time. It points to the
maintenance_tasksgem for that work; see our checklist for evaluating a Rails gem before adding it. - Adding a NOT NULL column without a default to a table that has rows. The migration fails on the first existing row. Add the column as nullable, backfill it, then add the constraint.
- Forgetting
from:/to:or the column type. The migration runs forward and only fails on rollback, usually at the worst moment. - Building a large index in a locking transaction. On a busy PostgreSQL table, use
algorithm: :concurrentlywithdisable_ddl_transaction!.
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.
GuidesUpgrading from Rails 8.0 to 8.1
Support dates, Ruby first, then bundle update, app:update and the new defaults: the 8.0 to 8.1 routine.
GuidesEvaluating a Rails gem
A practical checklist for judging a Ruby gem: maintenance signals, compatibility with Rails 7 and 8, dependencies, licence, and security advisories with bundler-audit.
Category guidesSoft deletes
Discard adds a discarded_at column and two scopes; Paranoia and acts_as_paranoid override destroy. Which one, and when to skip soft deletes entirely.