ActiveRecord: migrations
This course covers ActiveRecord migrations: ordered, versioned files that describe each change to a database's structure. It shows how bin/rails generate migration creates a timestamped file and how the timestamp sets the run order. It explains the change method, create_table, null: false and t.timestamps, and why Migration[8.0] carries a version number. It then covers applying pending migrations with db:migrate, reading db/schema.rb as a generated snapshot, and undoing the latest step with db:rollback. A final lesson follows one CreateArticles migration from file to table.
What you'll learn
- ✓What a migration is and why it is committed to git
- ✓Generating migrations and how timestamps set the run order
- ✓Writing the change method with create_table and column options
- ✓Applying pending migrations with db:migrate and checking db:migrate:status
- ✓Reading db/schema.rb and loading it with db:schema:load
- ✓Undoing the latest migration with db:rollback
What is a migration?
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…
Read the full lesson free →Curriculum
7 lessonsWhat is a migration?
A migration is one ordered, versioned change to database structure, committed to git so every environment matches.
Generating a migration
bin/rails generate migration creates a timestamped file, and names like Create<Table> let the generator pre-fill the body.
def change: one method, both directions
The change method uses create_table, null: false and t.timestamps, and Rails reverses common operations on its own.
bin/rails db:migrate: applying what's pending
bin/rails db:migrate applies only pending migrations, oldest first by timestamp, and db:migrate:status shows which ones ran.
schema.rb: the result, not the source
db/schema.rb is a generated snapshot whose version marks the last migration applied, and db:schema:load reaches it faster.
bin/rails db:rollback: undoing the last step
bin/rails db:rollback undoes the most recent migration by running it backward, useful for fixing a mistake right away.
Putting it together: from file to table
One CreateArticles migration is followed from generation to table, tying together naming, change, db:migrate, schema.rb and rollback.