In a Rails migration, which calls can a change method reverse automatically, and when must you write up and down instead?
answer
- the command recorder replays in reverse
- create, add and rename invert cleanly
- remove_column needs its type
- change_column and execute have no inverse
- error appears only on rollback
basics
~20 sOn rollback Rails replays change through a command recorder and inverts each call: create_table, add_column, add_index, add_reference, add_foreign_key and rename_column invert cleanly. change_column, execute and under-specified removals raise ActiveRecord::IrreversibleMigration, so those need up and down.
solid answer
~40 sA `change` method is run forwards on `db:migrate`. On rollback Rails runs the same method inside `revert`: an `ActiveRecord::Migration::CommandRecorder` records each schema call, inverts it, and replays the inverses in reverse order. Pairs with an obvious opposite work: `create_table`/`drop_table`, `add_column`/`remove_column`, `add_index`, `add_reference`, `add_foreign_key`, `add_check_constraint`, `rename_column` (names swapped) and `change_column_null` (flag flipped). Some removals work only with enough information: `remove_column` needs the type, `change_column_default` needs `from:` and `to:`, `drop_table` needs a block, `remove_foreign_key` needs the target table. `change_column` and raw `execute` have no inverse, so rollback raises `ActiveRecord::IrreversibleMigration`. That error appears at rollback time, not when the migration first runs, so for those calls you write `up` and `down` (or wrap the SQL in `reversible`).
code
ruby · 7 linesclass AddStatusDefaultToShipments < ActiveRecord::Migration[8.1]
def change
change_column_default :shipments, :status, from: nil, to: "pending"
change_column_null :shipments, :status, false
rename_column :shipments, :weight, :weight_grams
end
endgo deeper
Recall that change runs backwards on rollback and name a few calls that reverse cleanly and two that do not: change_column and execute.
Explain the command recorder, the extra arguments that make removals reversible (type, from: and to:, the target table), and why the error appears only on rollback.
Show the habit that prevents broken rollbacks: up/down or reversible for SQL and type changes, a deliberate IrreversibleMigration where data is destroyed, and a rollback run before merge.
Decide how much the team relies on rollbacks at all versus forward fixes, and what review rule keeps every migration either reversible or explicitly marked as not.
## How change runs in both directions A migration either defines `change` or a pair of methods, `up` and `down`. When Rails migrates up, it simply calls `change`. When it migrates down, it calls `change` again inside `revert`. In that mode the connection is swapped for an `ActiveRecord::Migration::CommandRecorder`, which does not touch the database. It writes each call down (`add_column`, `add_index` and so on), works out the inverse of each one, and then runs the inverses **in reverse order**. A migration that created a table and then indexed it is undone by removing the index and then dropping the table. If a class defines both `change` and `up`/`down`, Rails uses `change`; the pair is for migrations that cannot be described as one reversible sequence. ## Calls the recorder can invert | Call in `change` | Inverse run on rollback | Condition | |---|---|---| | `create_table :shipments do ... end` | `drop_table :shipments` | none | | `add_column :shipments, :tracking_number, :string` | `remove_column` | none | | `add_index`, `add_reference`, `add_timestamps` | the matching `remove_*` | none | | `add_foreign_key`, `add_check_constraint` | the matching `remove_*` | none | | `rename_column :shipments, :weight, :weight_grams` | rename back | none | | `change_column_null :shipments, :status, false` | the same call with `true` | none | | `remove_column :shipments, :notes, :text` | `add_column` | the type must be given | | `change_column_default :shipments, :status, from: nil, to: "pending"` | `from:` and `to:` swapped | both options given | | `drop_table :legacy_labels do |t| ... end` | `create_table` with that block | a block or options given | | `remove_index :shipments, column: :tracking_number` | `add_index` | the column given | | `remove_foreign_key :shipments, :couriers` | `add_foreign_key` | the target table given | `change_table :shipments do |t| ... end` is fine as long as every call inside it is invertible: `t.rename` and `t.index` are, while `t.change` and a `t.remove` without `type:` are not. ## Calls with no inverse - **`change_column`** changes a type or options, and nothing records what the column was before. Rails cannot guess it. - **`execute`** runs raw SQL. The recorder cannot read SQL and work out its opposite. - **Removals without enough detail**: the conditions in the table above. - **Plain Ruby**, such as a model update, is not recorded at all. It simply runs again whenever `change` runs, in either direction. In each recorded case Rails raises `ActiveRecord::IrreversibleMigration` with a message suggesting `up`/`down` or `reversible`. The catch is **timing**: the migration runs up without complaint, and the error appears only when someone tries to roll it back, often on a teammate's machine weeks later. ## A rollback, step by step Take a `change` method that creates `shipments`, adds a unique index on `tracking_number`, and renames `weight` to `weight_grams`. On `bin/rails db:rollback` Rails: 1. Calls `change` with the command recorder in place of the connection, so nothing reaches the database yet. 2. Turns each call into its inverse as it is recorded: `drop_table`, `remove_index`, and a rename from `weight_grams` back to `weight`. 3. Reverses the list, so the newest command is undone first. 4. Runs the inverses: the rename back, then the index removal, then the drop. 5. Deletes the migration's row from the version table, in the same transaction on databases with transactional DDL. If step 2 meets a command without an inverse, it raises before the recorder sends any SQL, so the schema is left as it was. ## Writing up and down ```ruby class WidenShipmentWeight < ActiveRecord::Migration[8.1] def up change_column :shipments, :weight_grams, :bigint end def down change_column :shipments, :weight_grams, :integer end end ``` `up` and `down` are ordinary methods: Rails calls one or the other, and you are responsible for making `down` the true opposite. Where a step genuinely cannot be undone (a column of data was dropped and summarised), `down` can raise `ActiveRecord::IrreversibleMigration` on purpose, so a rollback stops loudly instead of pretending. ## Choosing between them 1. Default to `change`, written so every call is invertible, which usually means passing the type, `from:`/`to:` or the target table. 2. When one step is SQL or a type change inside an otherwise reversible migration, keep `change` and wrap that step in `reversible`. 3. Use `up` and `down` when most of the migration is one-directional or the two directions differ in more than a call or two. 4. Prove the down path before merging: run the migration, roll it back, run it again.
- Why does a migration with change_column in change succeed on db:migrate and fail later?Migrating up just runs the method, and `change_column` executes normally. Only rollback asks the command recorder for inverses, and `change_column` has none, so `ActiveRecord::IrreversibleMigration` is raised then. Rolling back and re-running a new migration before merging catches this while it is still cheap.
- How do you make change_column_default reversible?Pass both values: `change_column_default :shipments, :status, from: nil, to: "pending"`. The recorder inverts it by swapping them. Called with just a new default, it raises `ActiveRecord::IrreversibleMigration` on rollback because Rails does not know the old default.
- When is it right for down to raise ActiveRecord::IrreversibleMigration deliberately?When the up direction destroys information that cannot be rebuilt, such as dropping a column after copying a summary elsewhere. Raising in `down` makes a rollback stop with a clear message instead of recreating an empty column and pretending the data came back.
The command recorder is like an editor's undo history: every recorded edit has a known opposite, applied newest first. A free-hand change it never understood, like raw SQL, leaves nothing to undo.
- change_column is reversible because Rails remembers the old column type
- remove_column can never appear in a reversible change method
- Rails raises IrreversibleMigration as soon as the migration runs up
- Rails reverses raw SQL in execute by parsing the statement
- A model update inside change is skipped when the migration rolls back