Understanding Rails

Understanding Rails · Season 3: Active Record in depth

Migrations in depth

Episode 17 · deep dive · about 7 minutes · Rails 8.1 · by

How was this episode?

The series' author reads every note, and no one else sees it. When something is wrong or unclear, it gets fixed and the episode re-cut. How this series stays right.

Was it clear?

Not endorsed yet. Are you a Rails developer? What's an endorsement?

Endorse this version To endorse: create an account, confirm your email, then link GitHub.

What changed

  • Version 4, November 21, 2026: A replay showed the rollback dropped the column's default, so the example now changes it from false to true.
  • Version 3, November 20, 2026: Made the "prefer" migration example reversible, so it follows the episode's own rule.
  • Version 2, November 20, 2026: The Solid trio's databases are for production. In development a new app caches in memory and runs jobs in its own process.

Reversible changes, schema.rb, rollbacks, and changing a column safely.

Free to watch. If it helped, support the series.

Transcript

0:00 Migrations in depth

Episode seventeen. Migrations in depth. Your database changes as your app grows. Migrations are how those changes are written down, shared, and undone. Today: how they run, how they reverse, and how to change a table that already holds data.

0:20 Why migrations

Without migrations, you'd change the database by hand: on your computer, then on every teammate's, then on the server, hoping nobody missed a step. A migration is that change, written in Ruby, in a file. Run the same files, in the same order, and every database ends up the same.

0:39 Generating one

Start with the generator. Bin slash rails generate migration, AddTitleToNotes, title colon string. Rails reads the name: add title, to notes. So it writes the change for you, in one line: add column, notes, title, string.

0:55 The version

Look at the file's name. It starts with a timestamp: the year, month, day, hour, minute, and second it was made. That number is the migration's version. It puts every migration in the order it was written, across a whole team.

1:11 db:migrate

Bin slash rails db colon migrate runs every migration that hasn't run yet. Rails prints each step: migrating, the add column it ran and how long it took, then migrated.

1:24 schema_migrations

How does Rails know what has already run? A table in your database, schema migrations, holds one row for each version that ran. Rails compares the files in db slash migrate with that table, and runs only the files it doesn't find there.

1:41 db:migrate:status

You can see that comparison yourself. Db colon migrate colon status lists every migration, and whether it's up, which means it ran, or down.

1:52 schema.rb

After every migration, Rails writes db slash schema dot rb: the whole shape of your database as it is now, in one file. Its version is the newest migration that ran. Commit it. A new teammate's database is built from this file in one step, instead of replaying every migration ever written. And never edit it by hand, because the next migration rewrites it.

2:16 change

Now look at the method itself: change. Not up, not down, just change. Rails knows how to undo add column: it's remove column. So one method describes both directions.

2:28 db:rollback

Bin slash rails db colon rollback undoes the last migration. Rails runs it backwards: reverting, remove column, reverted. And status shows it down again.

2:41 redo

Db colon migrate colon redo does both in one step: it rolls back, then migrates again. It's the quickest way to prove a migration really can be undone.

2:52 STEP

To go back further, add step. Db colon rollback, step equals two, undoes the last two migrations, newest first. Status now shows both of them down. Migrate again, and they run in order.

3:06 Irreversible migrations

But not every change can be undone from the change alone. Take change column, from string to text. Going back, Rails can't know what the column was before. So when you roll it back, Rails stops, with an irreversible migration error, and a message that tells you the two ways out.

3:25 up and down

The first way: write up and down yourself. Up changes the column to text. Down changes it back to string. Now the rollback works, because you've told Rails both directions.

3:37 reversible

The second way keeps the change method. Inside it, a reversible block names each direction: direction dot up changes the column to text, and direction dot down changes it back. Use it when most of a migration reverses on its own, and only one part needs help.

3:55 Data already there

The hardest migrations change a table that already holds data. Say every note needs a slug, and it must never be empty. Add the column with null false, and the migration fails: not null constraint failed. The note that already exists has no slug to give.

4:12 Three safe steps

So do it in three steps. Add the column, allowing empty values. Fill in every existing row, here with one SQL update. Then change column null, to false. Each step works with the data that's really there, and our one note becomes note dash one.

4:30 A default

When there's a sensible starting value, it's simpler. Add pinned, a boolean, with default false and null false. Every existing note gets false, and the rule holds from the start.

4:42 A unique index

Rules can live in the database itself. Add an index on slug, with unique true, and the database refuses a second note with the same slug, even if your Ruby code forgets to check. Try it, and you get record not unique: unique constraint failed. Indexes also make lookups by slug fast.

5:02 Models in migrations

One trap to know. In a migration, avoid calling your models, like Note dot update all. Migrations live for years, and your Note class keeps changing. A year from now, a fresh database replays this file against code that no longer matches it. Plain SQL, and the migration's own methods, stay true. Keep them reversible: tell change column default what it changes from and to, and put SQL inside reversible.

5:29 Expand, then contract

On a busy server, there's one more danger. Rename a column, and the code that's still running asks for the old name, and fails. The safe pattern is expand, then contract: add the new column, move the code over to it, and only later remove the old one.

5:45 The Solid databases

One more Rails 8 detail. In production, your app has more than one database: the Solid trio's queue, cache, and cable each keep their own. Their shapes live in queue schema, cache schema, and cable schema, beside schema dot rb. In development, a new app doesn't use them: it caches in memory, and runs jobs in its own process.

6:08 The rules

So, the rules. One change per migration. Make every migration reversible, and prove it with redo. Never edit a migration that has already run on someone else's database: write a new one. And commit schema dot rb along with it.

Next: associations, and how one model connects to another.

Check your understanding

  1. You run bin/rails db:migrate twice in a row. Why does the second run do nothing?

    • Rails compares file dates with the database's last change time
    • Each migration deletes its own file after it runs
    • Rails reads schema.rb to guess what ran
    • Each migration that ran left its version in the schema_migrations table, so Rails skips it
    Show answer

    Each migration that ran left its version in the schema_migrations table, so Rails skips it. Rails adds a row with the migration's version to schema_migrations when it runs. Files whose versions are already there are skipped. Source: Rails Migration Version Control, Active Record Migrations (Rails Guides 8.1).

  2. A change method calls change_column :notes, :title, :text. You run bin/rails db:rollback. What happens?

    • Rails stops with an irreversible migration error
    • The column goes back to string
    • The column is removed
    • Nothing happens, and the migration is marked down
    Show answer

    Rails stops with an irreversible migration error. change_column is not reversible on its own, because Rails can't know the old type. Write up and down, or use reversible. Source: Changing Columns, Active Record Migrations (Rails Guides 8.1).

  3. Your notes table already has one note. You add a slug column and want it NOT NULL. What makes change_column_null :notes, :slug, false succeed?

    • Nothing extra: Rails fills in empty slugs for you
    • Fill in a slug for every existing note first
    • Run it inside reversible
    • Add a unique index first
    Show answer

    Fill in a slug for every existing note first. change_column_null applies to existing rows too, so every note must already have a slug. Source: Changing Columns, Active Record Migrations (Rails Guides 8.1).

  4. Why should a migration avoid calling your models, like Note.update_all?

    • Models can't connect to the database during a migration
    • Model calls are slower than SQL
    • Your model code keeps changing, so an old migration may break when it is replayed later
    • Migrations can only use the change method
    Show answer

    Your model code keeps changing, so an old migration may break when it is replayed later. Old migrations can fail when they rely on application code that changes separately from them. Source: What are Schema Files for?, Active Record Migrations (Rails Guides 8.1).

Sources

Every example in this episode was run on Rails 8.1.4.1 and Ruby 4.0.2.

Comments

Sign in to comment or sign up.