guest@websec ~ % man r03-migrations
Migrations
A migration is a small Ruby file that changes the database schema one step forward, and knows how to step back. This whole lesson is about doing that safely.
bin/rails db:migrate, commit both the migration and the updated db/schema.rb. Once a migration is merged, never edit it. Write a new one.Where migrations live
db/ ├── migrate/ │ ├── 20261101090000_create_client_applications.rb │ ├── 20261101090100_create_roles.rb │ ├── 20261102100000_add_webhook_url_to_client_applications.rb │ └── 20261103110000_add_active_name_index_to_roles.rb ├── schema.rb # generated snapshot of the whole database; committed └── seeds.rb # sample data for bin/rails db:seed
file name | YYYYMMDDHHMMSS_what_it_does.rb. The 14-digit UTC timestamp is the migration's version; the generator writes it for you. |
class name | CamelCase of the rest of the file name: add_webhook_url_to_client_applications.rb → AddWebhookUrlToClientApplications. A mismatch fails to load. |
Migration[8.1] | the Rails version the migration was written for, so old migrations keep their old behaviour after upgrades |
schema_migrations | a table in each database with one row per version that has run. That table, not the files, decides what is “up”. |
db/schema.rb | rewritten after every migrate/rollback. New databases are built from it (db:prepare, db:schema:load), not by replaying every migration. |
Migrate and roll back: by step or by version
| command | what runs |
|---|---|
bin/rails db:migrate | every pending migration, oldest first |
bin/rails db:rollback | down on the newest migration that is up |
bin/rails db:rollback STEP=3 | down on the newest three, newest first |
bin/rails db:migrate:redo STEP=2 | roll back two, then migrate them again |
bin/rails db:migrate VERSION=20261102100000 | move the schema to that version: up for pending files up to it, down for newer files |
bin/rails db:migrate:up VERSION=… | up on that one file only |
bin/rails db:migrate:down VERSION=… | down on that one file only, even if newer ones are up |
bin/rails db:migrate:redo VERSION=… | down then up on that one file |
bin/rails db:migrate:status | up/down for every file |
bin/rails RAILS_ENV=test db:migrate | same, against another environment's database |
Things to try: db:migrate, then db:rollback STEP=2 (the two newest go down, newest first). db:migrate VERSION= the third file (only it comes back up). Then db:migrate:down VERSION= create_client_applications while roles is up: Postgres refuses, because a foreign key depends on it. Order matters.
Creating a table
class CreateRoles < ActiveRecord::Migration[8.1]
def change
create_table :roles, id: :uuid do |t| # uuidv7() default from our initializer
t.references :client_application, null: false, foreign_key: true, type: :uuid
t.text :name, null: false
t.text :description, default: ""
t.text :permissions, array: true, default: [], null: false
t.text :status, default: "active"
t.datetime :deleted_at # required by SoftDeletable
t.timestamps # created_at, updated_at
end
add_index :roles, :status
add_index :roles, :deleted_at
end
endid: :uuid, deleted_at with an index, timestamps. Required columns get null: false; booleans, arrays and status columns get a default. The database should reject bad data even if a model validation is skipped.Changing a table
class AddWebhookUrlToClientApplications < ActiveRecord::Migration[8.1]
def change
add_column :client_applications, :webhook_url, :text, default: ""
end
endRails can reverse most commands inside change on its own: create_table, add_column, add_index, add_reference, rename_column, add_foreign_key. A few need help:
# remove_column: give the type so rollback can re-create it remove_column :users, :legacy_code, :text # change_column_default: give from/to change_column_default :roles, :status, from: nil, to: "active" # anything else: write up and down def up change_column :users, :email, :citext end def down change_column :users, :email, :text end
Unique index on several columns
A user may hold a role once. Neither column is unique alone (a user has many roles, a role has many users); the pair is. Put both columns in one unique index:
class CreateUserRoles < ActiveRecord::Migration[8.1]
def change
create_table :user_roles, id: :uuid do |t|
t.references :user, null: false, foreign_key: true, type: :uuid # index on user_id
t.references :role, null: false, foreign_key: true, type: :uuid # index on role_id
t.text :status, default: "active"
t.datetime :deleted_at
t.timestamps
end
add_index :user_roles, [:user_id, :role_id], # order matters (see below)
unique: true,
where: "deleted_at IS NULL", # only live rows must be unique
name: "index_user_roles_on_user_id_role_id_where_active"
end
end
# also valid, inside create_table:
# t.index [:user_id, :role_id], unique: trueTry: insert alice + hr_viewer twice with no index (duplicates get in). Switch to the unique index: Postgres refuses to build it while duplicates exist. Soft-delete one, then compare the plain and partial index: the plain one still counts the deleted row; the partial one lets alice get the role again, and blocks a restore that would create a second live copy.
Column order
A multi-column index is sorted by the first column, then the second. It can serve queries on user_id alone (user.user_roles), but not on role_id alone. That’s why t.references :role keeps its own index. Put the column you filter by most often first.
Pair it with a validation
class UserRole < ApplicationRecord
validates :role_id, uniqueness: {
scope: :user_id, # same columns as the index
conditions: -> { not_deleted }, # same WHERE as the index
message: "has already been assigned to this user",
}
end- The validation gives a friendly 400 with
details. The index is the real guarantee: two requests arriving at the same moment can both pass the validation, and only the index stops the second insert (raisingActiveRecord::RecordNotUnique). - Keep them in sync. The uniqueness validator ignores
default_scope, so withoutconditions: -> { not_deleted }it counts soft-deleted rows and refuses to re-add a role the partial index would allow.Useralready does this forusername; checkUserRole. - In Postgres,
NULLs never collide: two rows withrole_id = NULLboth fit a unique index. Usenull: false, ornulls_not_distinct: true(Rails 7.1+, Postgres 15+).
Indexes for soft delete
We never really delete rows; we set deleted_at. A plain unique index on name would block re-creating a role with the name of a deleted one. A partial unique index only covers live rows:
class AddActiveNameIndexToRoles < ActiveRecord::Migration[8.1]
def change
add_index :roles, [:client_application_id, :name],
unique: true,
where: "deleted_at IS NULL",
name: "index_roles_on_ca_id_name_where_active"
end
endBig tables
class AddIndexToUserRolesStatus < ActiveRecord::Migration[8.1]
disable_ddl_transaction! # CONCURRENTLY can't run inside a transaction
def change
add_index :user_roles, :status, algorithm: :concurrently
end
endA normal index build locks writes on the table. On a large production table, build it concurrently.
A session at the terminal
Other database commands
| command | when |
|---|---|
bin/rails db:create | first setup |
bin/rails db:prepare | create + load schema, or migrate if it exists |
bin/rails db:schema:load | build a fresh DB from schema.rb (fast; never on production) |
bin/rails db:seed | run db/seeds.rb |
bin/rails db:reset | drop + create + load + seed: local only |
Rules we follow
- Never edit a merged migration. Other machines and production already ran it; they will never see your edit. Write a new migration.
- Commit
schema.rbwith the migration. Reviewers read the schema diff, not just the migration. - One change per migration, named for what it does.
- Run
db:migrate:redobefore pushing, to prove rollback works. - Don't use app models inside migrations. The model may change later and break old migrations. Use SQL or
update_allon a tiny local class. - Index foreign keys and anything you filter on (
status,deleted_at). - After migrating, the
== Schema Informationcomment at the top of each model is refreshed by theannotaterbgem. Commit those changes too.
Check yourself
A column name in last month's migration has a typo. That migration is already on production. What do you do?
Production will never re-run the old file, and schema.rb is generated. A new migration is the only change that reaches every database.
Why does remove_column :users, :legacy_code fail on rollback?
Pass the type (remove_column :users, :legacy_code, :text) and it becomes reversible.