What is a migration?

Free preview 2 min to read

Where the articles table came from

Every course since ActiveRecord: model introduction assumed an articles table existed for Article.find, .create and .all. None explained where it came from, or how it could gain a column later without breaking saved rows. A migration fills that gap: one ordered, versioned instruction describing one change to the database's structure.

Versioned, like code already is

The Git courses covered committing changes one at a time, each building on the last in a known order. A migration applies that idea to a database's structure. In this project's history, CreateUsers runs before CreateCourses: small ordered steps, not one big setup script you can't repeat.

db/migrate/20260226000000_create_users.rb
db/migrate/20260226000001_create_courses.rb
db/migrate/20260226000002_create_lessons.rb

These are this project's first migration files, each named with a timestamp prefix. The timestamp decides the order they run in; lesson 2 covers where it comes from.

Why not edit the database by hand?

Changing a table by hand works on one machine, until a teammate's database or a production server needs the same change. A migration is a file committed to git, so any teammate or deploy can run it and reach the same structure, in the same order, every time.

Key takeaways

  • A migration is one ordered, versioned change to the database's structure.
  • This project's migration files are timestamp-prefixed and run in timestamp order.
  • Committed to git, a migration lets any teammate or deploy reach the same structure.
Lesson 1 of 7 · free

Keep going with lesson 2

Generating a migration

bin/rails generate migration creates a timestamped file, and names like Create<Table> let the generator pre-fill the body.

A free account also gives you the quizzes, your progress and notes, and the discussion.

Type to start searching...