In a Rails 8.1 migration, how do you create a shipments table that belongs to couriers, and what does t.references :courier add?
answer
- create_table yields a table definition
- courier_id column of type bigint
- index: true is the default
- foreign_key: defaults to false
- t.timestamps columns are NOT NULL
basics
~20 sCall create_table :shipments in the change method. Inside it, t.references :courier adds a bigint courier_id column and an index on it; a real foreign key constraint appears only with foreign_key: true, and NOT NULL only with null: false.
solid answer
~40 s`create_table :shipments do |t| ... end` builds one `CREATE TABLE` with an auto-incrementing `id` primary key, and `t.timestamps` adds `created_at` and `updated_at` as NOT NULL datetime columns. `t.references :courier` (alias `t.belongs_to`) expands to a `courier_id` column of type `:bigint` plus an index named `index_shipments_on_courier_id`, because `index:` defaults to `true`. It does **not** add a foreign key constraint unless you pass `foreign_key: true`, and the column stays nullable unless you pass `null: false`. So the line most courier apps want is `t.references :courier, null: false, foreign_key: true`. The whole migration lives in `change`, and Rails can reverse it on rollback by dropping the table.
code
ruby · 11 linesclass CreateShipments < ActiveRecord::Migration[8.1]
def change
create_table :shipments do |t|
t.references :courier, null: false, foreign_key: true
t.references :sender, foreign_key: { to_table: :users }
t.string :tracking_number, null: false
t.integer :weight_grams
t.timestamps
end
end
endgo deeper
Write the create_table block from memory and say exactly what t.references adds: courier_id, an index, and nothing else unless you pass foreign_key: true or null: false.
Explain each default of t.references (bigint, index on, foreign key off) and how to point the constraint at another table with to_table, plus why timestamps are NOT NULL.
Argue for database constraints next to model checks: which writers skip validations, and why null: false and foreign_key: true belong in the first migration rather than a cleanup later.
Set the team default: whether every reference ships with a constraint, how polymorphic links are policed without one, and how that choice shows up in code review.
## The migration in a courier app A courier app already has a `couriers` table. Each shipment is carried by one courier, so the new `shipments` table needs a column pointing at `couriers.id`. In current Rails this is one migration class: ```ruby class CreateShipments < ActiveRecord::Migration[8.1] def change create_table :shipments do |t| t.references :courier, null: false, foreign_key: true t.string :tracking_number, null: false t.string :status, null: false, default: "pending" t.integer :weight_grams t.timestamps end end end ``` The `[8.1]` after `ActiveRecord::Migration` pins the migration to Rails 8.1 behaviour, so an old migration keeps producing the same schema after an upgrade. The code sits in `change`, a method Rails can run forwards and, on rollback, backwards. ## What create_table does before you add a column - **Primary key.** By default the table gets an auto-incrementing `id` primary key. `id: false` skips it and `primary_key: :code` renames it. - **A table definition object.** The block receives `t`, an `ActiveRecord::ConnectionAdapters::TableDefinition`. Every `t.string`, `t.integer` or `t.references` call adds to that definition. - **One table statement.** Rails turns the definition into a `CREATE TABLE` that carries the foreign keys inline, followed by the index statements the adapter needs. - **Reversible.** On rollback, Rails turns `create_table` into `drop_table :shipments`. ## Column options that ride along Every `t.<type>` call takes the same family of options, and choosing them here is cheaper than a second migration later: - `null: false` makes the column NOT NULL; the database then rejects a row without a value. - `default: "pending"` sets a database default, used when an insert leaves the column out. - `index: true` on an ordinary column, such as `t.string :tracking_number, index: { unique: true }`, adds the index in the same block. - `limit:`, `precision:` and `scale:` size strings and decimals where the adapter supports them. - `comment:` stores a column comment on adapters that support comments. A unique index on `tracking_number` is the usual partner of a model's uniqueness validation: the validation gives a friendly message, the index is what actually stops two concurrent inserts from both succeeding. ## What t.references :courier expands to `t.references` (and its alias `t.belongs_to`) is shorthand for several pieces. Each one has a default and an option that changes it: | Piece | Default | Option to change it | |---|---|---| | `courier_id` column | type `:bigint`, nullable | `type:`, `null: false` | | Index `index_shipments_on_courier_id` | added (`index: true`) | `index: false`, `index: { unique: true }` | | Foreign key constraint to `couriers.id` | **not added** (`foreign_key: false`) | `foreign_key: true` or a hash of options | | `courier_type` column | not added | `polymorphic: true` | Two details trip people up: 1. **The foreign key is opt-in.** Without `foreign_key: true` the database will happily store a `courier_id` of 999 that matches no courier. The model's `belongs_to :courier` checks presence in Ruby, but only the constraint stops a bad row written by `update_column`, `insert_all` or raw SQL. 2. **A different table name goes in the foreign key hash.** A `sender` that points at `users` is written `t.references :sender, foreign_key: { to_table: :users }`; the column is still `sender_id`. A polymorphic reference cannot have a foreign key, because one column points at several tables. `t.references :trackable, polymorphic: true, foreign_key: true` raises `ArgumentError` when the migration runs. ## t.timestamps `t.timestamps` adds `created_at` and `updated_at` as `datetime` columns. Inside `create_table` both default to `null: false`, and on the bundled adapters they get `precision: 6` (microseconds). Active Record fills them in Ruby when it creates or updates the record; they are not database defaults, so a raw `INSERT` that omits them fails the NOT NULL check. ## Adding the same reference to an existing table When the table already exists, `add_reference` does the same job outside `create_table`: ```ruby add_reference :shipments, :depot, foreign_key: true ``` It applies the same defaults (bigint column, index on, foreign key off unless asked) and is also reversible: rollback runs `remove_reference`, which drops the column together with its index and constraint. ## Mistakes interviewers listen for - Expecting `t.references` to create a foreign key on its own; it creates a column and an index. - Adding a second `add_index :shipments, :courier_id` after `t.references`, which fails because the database already has an index named `index_shipments_on_courier_id`. - Writing `t.integer :courier` and expecting Active Record to find `courier_id`. - Treating `t.belongs_to` and `t.references` as different methods; they are the same. - Forgetting `null: false` on a reference the domain says is required, so the database accepts shipments with no courier.
- How do you reference a table whose name does not match the reference, such as a sender stored in users?Keep the reference name and point the constraint elsewhere: `t.references :sender, foreign_key: { to_table: :users }`. The column is `sender_id`, the index is `index_shipments_on_sender_id`, and the foreign key references `users.id`. The model then needs `belongs_to :sender, class_name: "User"` so Active Record knows which class to load.
- Why add null: false when the model already has belongs_to :courier?`belongs_to` validates presence only when Active Record saves through validations. `update_column`, `insert_all`, `upsert_all` and raw SQL skip validations, so a nullable `courier_id` can still end up NULL. `null: false` makes the database itself reject the row, which is the guarantee that holds for every writer.
- What happens if you call t.references :trackable, polymorphic: true, foreign_key: true?The migration raises `ArgumentError` ("Cannot add a foreign key to a polymorphic relation"). A polymorphic reference adds `trackable_type` and `trackable_id`, and the id can point at rows in several tables, so no single foreign key constraint can describe it.
- t.references :courier creates a foreign key constraint by default
- t.references :courier makes an integer column called courier
- You must add a separate add_index for courier_id after t.references
- t.timestamps columns accept NULL unless you pass null: false
- t.belongs_to builds a different column than t.references