Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Active Record Models

Migrations and the Schema

Learn Rails migrations: create tables, add columns and indexes, run and roll back changes, and what schema.rb is for. Includes a runnable migration runner stand-in with versions and rollback.

A database changes over time: you add a table, rename a column, create an index. If every developer changed their own database by hand, no two copies would match. Rails solves this with migrations: small Ruby files that describe a change, each with a timestamp version. Everyone runs the same files in the same order, so every database (yours, a teammate's, production) ends up with the same structure.

Migrations need Rails and a database, so the Rails code is read-only. The runnable stand-in is a tiny migration runner that tracks versions, runs changes and rolls them back.

Writing a migration

You usually generate one. The name tells Rails what to do, and the column list fills in the body:

Terminal
# read-only
bin/rails generate migration CreateArticles title:string body:text published:boolean
bin/rails generate migration AddAuthorToArticles author:references
bin/rails generate migration AddSlugToArticles slug:string:index
Ruby
# db/migrate/20260312091500_create_articles.rb  (read-only)
class CreateArticles < ActiveRecord::Migration[8.0]
  def change
    create_table :articles do |t|
      t.string  :title, null: false
      t.text    :body
      t.boolean :published, default: false, null: false

      t.timestamps          # created_at and updated_at
    end

    add_index :articles, :title
  end
end

The number in the file name is the version. The class name must match the file name (create_articles becomes CreateArticles). ActiveRecord::Migration[8.0] pins the behaviour to the Rails version that created the file, so later Rails upgrades will not change what an old migration does.

Rails adds an id primary key to every table automatically and t.timestamps fills in created_at and updated_at, which Active Record keeps up to date.

Column types and options

Common types: string (short text), text (long text), integer, bigint, float, decimal (use for money, with precision and scale), boolean, date, datetime, json, references. Common options:

Option Meaning
null: false The database rejects NULL
default: 0 Value used when none is given
limit: 100 Maximum length for string columns
index: true Create an index on the column
unique: true (with an index) Database-level uniqueness
foreign_key: true Add a foreign key constraint

t.references :author, foreign_key: true creates author_id (a bigint), an index on it and the foreign key constraint.

Running and rolling back

Terminal
# read-only
bin/rails db:migrate           # run every pending migration
bin/rails db:migrate:status    # list up/down per version
bin/rails db:rollback          # undo the last migration
bin/rails db:rollback STEP=3   # undo the last three
bin/rails db:migrate:redo      # rollback + migrate again (good for testing)
bin/rails db:prepare           # create the DB if missing, load schema, run seeds when new

Rails records every applied version in a table called schema_migrations. db:migrate runs the files whose version is not in that table, in order. Rolling back removes the version and undoes the change.

The change method works for both directions as long as Rails can reverse each step. create_table, add_column, add_index and add_reference are reversible. For steps Rails cannot reverse (raw SQL, removing a column without telling Rails its type), write up and down separately, or use reversible:

Ruby
# read-only
class SplitName < ActiveRecord::Migration[8.0]
  def up
    add_column :users, :first_name, :string
    add_column :users, :last_name, :string
    execute "UPDATE users SET first_name = name"
  end

  def down
    remove_column :users, :first_name
    remove_column :users, :last_name
  end
end

Stand-in: a tiny migration runner

This stand-in keeps a schema Hash (table name to column list) and a schema_migrations list. Each migration has up and down methods. It reproduces db:migrate, db:rollback and db:migrate:status.

Ruby Stand-in: migrate and rollback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Run it and watch the order: the migrations run oldest first, rollback undoes only the newest, and running migrate again applies exactly the missing one. That is the whole idea behind the real command.

schema.rb and structure.sql

After every migration Rails dumps the current database structure into db/schema.rb. It is generated, not written by hand, and it shows the final state:

Ruby
# db/schema.rb  (read-only, generated)
ActiveRecord::Schema[8.0].define(version: 2026_03_12_091500) do
  create_table "articles", force: :cascade do |t|
    t.string "title", null: false
    t.text "body"
    t.boolean "published", default: false, null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["title"], name: "index_articles_on_title"
  end
end

Commit schema.rb to Git. A new teammate (or the test database) can run bin/rails db:schema:load and get the whole structure in one step instead of replaying hundreds of old migrations. If you use database features Ruby cannot describe (views, triggers, custom types), set config.active_record.schema_format = :sql to dump db/structure.sql instead.

Good migration habits

  • Never edit a migration that has been shared. Teammates and production already ran it. Write a new migration instead. Editing is fine only while it exists on your machine alone (roll back, edit, migrate).
  • Keep migrations small and focused. One purpose each makes rollbacks easy.
  • Constraints in the database matter. null: false, unique indexes and foreign keys protect data even when code has a bug.
  • Be careful with big tables. Adding an index or a column with a default can lock a large table. Tools such as strong_migrations warn about risky operations.
  • Use data migrations sparingly. Heavy data changes belong in a rake task or a job, not in a schema migration.

Running bin/rails db:drop or db:reset erases data. These commands are for development. In production, Rails protects the database with an environment check, but never rely on that alone.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the number in a migration file name represent?

    The timestamp version orders migrations and is stored in schema_migrations.
  2. 2. Which command undoes the most recent migration?

    db:rollback runs the reverse of the latest applied migration.
  3. 3. You find a typo in a migration your team already ran in production. What should you do?

    Shared migrations are history. Fix forward with a new one.
  4. 4. Which type is the best choice for storing prices?

    decimal avoids floating-point rounding errors in money.
  5. 5. What is db/schema.rb?

    Rails regenerates schema.rb after migrations; load it to create a fresh database fast.

Summary

  • A migration is a versioned Ruby file that describes one database change; everyone runs the same files in order.
  • change is reversible for common steps; use up and down (or reversible) otherwise.
  • db:migrate, db:rollback and db:migrate:status apply, undo and list versions, tracked in schema_migrations.
  • schema.rb is a generated snapshot; commit it and use db:schema:load for fresh databases.
  • Never edit shared migrations, keep them small, and use database constraints.

Next: CRUD with Active Record