In Rails, why does naming a migration AddTrackingNumberToShipments make bin/rails generate migration write the add_column call for you?
answer
- the generator parses the file name
- table name comes after _to_
- RemoveXFromY writes remove_column with a type
- CreateX switches to the create_table template
- any other name gives an empty change
basics
~10 sThe migration generator reads the name: add_...to<table> fills change with add_column calls on that table, remove_...from<table> with remove_column calls, and create_<table> with a create_table block; any other name leaves change empty.
solid answer
~40 s`bin/rails generate migration` underscores the name and matches it against a few patterns. `add_tracking_number_to_shipments` matches `add_..._to_<table>`, so the generator takes `shipments` as the table and writes one `add_column :shipments, :tracking_number, :string` per attribute you pass (an attribute of type `references` becomes `add_reference`). `remove_..._from_<table>` writes `remove_column` calls **with the column type**, which is what keeps the generated migration reversible. `create_<table>` switches to the `create_table` template, a name containing `join_table` with two attributes writes `create_join_table`, and anything else gives an empty `change` to fill in. The words between `Add` and `To` are only a label; the table always comes from the part after `_to_` or `_from_`.
code
bash · 4 linesbin/rails generate migration AddTrackingNumberToShipments tracking_number:string
bin/rails generate migration RemoveWeightGramsFromShipments weight_grams:integer
bin/rails generate migration CreateDepots name:string
bin/rails generate migration BackfillShipmentStatusgo deeper
Know the three name shapes, AddXToY, RemoveXFromY and CreateX, and say which method each writes and which table it targets.
Explain why the generated remove_column carries a type, and what happens with a name that matches no pattern or with no attributes.
Use names as documentation in review: a migration called BackfillShipmentStatus should not be dropping columns, and a duplicate class name is caught before merge.
Decide whether the team relies on generated bodies or treats them as drafts, and how naming conventions keep a long migration history searchable.
## The name is input, not just a label `bin/rails generate migration` (`bin/rails g migration`) writes a timestamped file under `db/migrate/`. Before it picks a template it turns the name into snake case and matches it against a few patterns. A courier app that needs a tracking number on shipments runs: ```bash bin/rails generate migration AddTrackingNumberToShipments tracking_number:string ``` and gets: ```ruby class AddTrackingNumberToShipments < ActiveRecord::Migration[8.1] def change add_column :shipments, :tracking_number, :string end end ``` The class name is the migration name, the file name is `<timestamp>_add_tracking_number_to_shipments.rb`, and the body is already written because the name told the generator which table to touch. ## The patterns the generator recognises | Name shape | Example | What `change` contains | |---|---|---| | `add_..._to_<table>` | `AddTrackingNumberToShipments` | `add_column :shipments, ...` per attribute; `add_reference` for a `references` attribute | | `remove_..._from_<table>` | `RemoveWeightGramsFromShipments` | `remove_column :shipments, :weight_grams, :integer` per attribute | | `create_<table>` | `CreateShipments` | a `create_table :shipments do |t| ... end` block | | contains `join_table`, two attributes | `CreateJoinTableShipmentsDepots shipments depots` | `create_join_table :shipments, :depots` | | anything else | `BackfillShipmentStatus` | an empty `change` method | Points worth saying out loud: - **The table comes from the end of the name.** In `AddTrackingNumberToShipments` the generator ignores `TrackingNumber` and uses what follows `_to_`; the columns come from the attributes you list. `AddTrackingNumberToShipments` with no attributes produces an empty `change`. - **Table names are pluralised** when the app pluralises table names (the default), so `AddNoteToShipment` still targets `shipments`. - **CamelCase and snake_case both work.** `add_tracking_number_to_shipments` gives the same class and file. - **The file name must be lowercase letters, digits and underscores** after conversion; anything else raises `ActiveRecord::IllegalMigrationNameError`. ## Why RemoveXFromY writes the column type A `change` method is reversible only when Rails can work out the opposite of every command. `remove_column :shipments, :weight_grams` without a type cannot be undone, because Rails would not know what column to re-add. The generator therefore writes `remove_column :shipments, :weight_grams, :integer` using the type from the attribute you pass. That is why `bin/rails g migration RemoveWeightGramsFromShipments weight_grams:integer` produces a migration that rolls back cleanly, while a hand-written `remove_column` with no type does not. ## Names must stay unique The migration name is also a Ruby class name. Two files that both define `AddTrackingNumberToShipments` make Rails raise `ActiveRecord::DuplicateMigrationNameError`, even though their timestamps differ. When a second change to the same table is needed later, give it a new, descriptive name such as `AddCarrierCodeToShipments`. ## The other templates in detail - **`create_<table>`** writes a `create_table` block with one `t.<type>` line per attribute and, by default, `t.timestamps`. `bin/rails g migration CreateDepots name:string` targets `depots`. - **Join tables.** A name that contains `join_table` and exactly two attributes, such as `CreateJoinTableShipmentsDepots shipments depots`, writes `create_join_table :shipments, :depots`. That builds a table with the two id columns and no primary key, with commented index lines to enable. - **References in an add migration.** An attribute typed `references` becomes `add_reference` instead of `add_column`, so `AddDepotToShipments depot:references` adds `depot_id` with its index and a foreign key, plus NOT NULL in an app whose `belongs_to` is required by default, which is what new apps get. - **Everything else** gets an empty `change`. Data fixes, renames and `change_column` calls are written by hand, so names such as `RenameWeightOnShipments` are documentation only. ## What the name does not decide - **Index and NOT NULL options** come from the attribute syntax after the name, which is the generator's own topic. - **The version** is the UTC timestamp the generator puts in front of the file name; the class name plays no part in ordering. - **What runs** is whatever ends up in the file. The generated body is a starting point; editing it before the first `db:migrate` is normal practice. A good habit is to read the generated file before migrating: if the name did not match a pattern, the empty `change` method is the first sign. ## Why interviewers ask The question checks two things at once. First, whether the candidate has generated migrations rather than copied them, because the `_to_` and `_from_` rule is something you notice by using it. Second, whether they connect the generated `remove_column` type to reversibility, which is the bridge to the harder question of which migration calls Rails can undo on its own.
- What does the generator write for bin/rails g migration AddTrackingNumberToShipments with no attributes?An empty `change` method in a class named `AddTrackingNumberToShipments`. The name tells the generator the action and the table, but the columns come only from the attributes on the command line, so with none listed there is nothing to write. You add `add_column :shipments, :tracking_number, :string` yourself before running `db:migrate`.
- Why can a hand-written remove_column :shipments, :weight_grams break db:rollback?On rollback Rails inverts each command in `change`. Inverting `remove_column` means re-adding the column, which needs its type. With no type Rails raises `ActiveRecord::IrreversibleMigration` ("remove_column is only reversible if given a type"). Passing `:integer` as the third argument fixes it.
- The migration name is only a label and never shapes the generated code
- AddTrackingNumberToShipments creates a new table called tracking_numbers
- RemoveXFromY generates remove_column without a type, so it cannot roll back
- Two migrations may share a class name as long as their timestamps differ
- The generator takes the table name from the word right after Add