ActiveRecord migrations: multi-table
This course covers ActiveRecord migrations that create or change several related tables in one file. Rails wraps each migration in one transaction by default, so a file lands completely or not at all. The lessons cover ordering create_table calls so a foreign key never points at a missing table. They explain when create_join_table fits and how to add a NOT NULL column to a table with rows. They also cover reversible, revert and ActiveRecord::IrreversibleMigration, and end with one combined example file.
What you'll learn
- ✓Why related schema changes belong in one migration file and one transaction
- ✓Ordering create_table calls so foreign keys reference tables that already exist
- ✓When create_join_table fits and why its indexes must be added by hand
- ✓Adding a NOT NULL column with a constant default to a table with rows
- ✓Writing data steps with reversible, revert and explicit up/down methods
- ✓Handling ActiveRecord::IrreversibleMigration when a rollback has no inverse
One file, one transaction, one related change
"ActiveRecord: migrations" taught what a migration is. ActiveRecord migrations: indexes taught how to make a single add_index safe on a table that already holds real rows. Both stayed inside one operation on one existing table. Neither asked what happens when a feature needs several new tables at…
Read the full lesson free →Curriculum
7 lessonsOne file, one transaction, one related change
Rails wraps each migration in one transaction, so related tables in one file land together or not at all.
Ordering: a table can't reference one that doesn't exist yet
A referenced table's create_table must come earlier in the file, or PostgreSQL raises PG::UndefinedTable.
create_join_table: a second way to relate two tables
create_join_table builds a pivot table with no id and no indexes, fitting links that carry no data.
Adding a NOT NULL column to a table that already has rows
A NOT NULL column with a constant default is metadata-only in PostgreSQL; without a default it fails.
reversible and revert: migrating down on purpose
reversible runs separate up and down code for data steps, and revert runs a step backwards.
When change can't reverse itself: IrreversibleMigration
Raw SQL with no inverse raises ActiveRecord::IrreversibleMigration on rollback; fix it with reversible or up/down.
Putting it together: one ordered, reversible file
One partners and partner_perks migration combines the transaction, table order, a constant default and a reversible data step.