skip to content

In a Rails migration, what do add_foreign_key and add_check_constraint create, and what must you pass so removing them stays reversible?

level: middleimportance: should knowfreq 40%

answer

  1. real constraints enforced by the database
  2. fk_rails_ and chk_rails_ default names
  3. on_delete: :cascade, :nullify or :restrict
  4. remove needs the target table or expression
  5. violations raise, they do not return false

basics

~10 s

add_foreign_key adds a FOREIGN KEY constraint named fk_rails_<hash>, add_check_constraint a CHECK constraint named chk_rails_<hash>. Both invert on rollback; removing them is reversible only if remove_foreign_key names the target table and remove_check_constraint repeats the expression.

solid answer

~30 s

`add_foreign_key :shipments, :couriers` runs `ALTER TABLE shipments ADD CONSTRAINT fk_rails_<10 hex chars> FOREIGN KEY (courier_id) REFERENCES couriers (id)`; options include `column:`, `primary_key:`, `name:`, `on_delete:` and `on_update:` (`:cascade`, `:nullify`, `:restrict`) and `if_not_exists:`. `add_check_constraint :shipments, "weight_grams > 0", name: "shipments_weight_positive"` adds a CHECK constraint, named `chk_rails_<hash>` when you give no name. Both are invertible in `change`. For the removals, `remove_foreign_key :shipments, :couriers` is reversible but `remove_foreign_key :shipments, column: :courier_id` is not, because rollback needs the target table; `remove_check_constraint` needs the expression so rollback can recreate it. A violating write raises `ActiveRecord::InvalidForeignKey` or `ActiveRecord::CheckViolation`; `save` does not return false for these.

code

ruby · 7 lines
ruby
class DropLegacyCourierLink < ActiveRecord::Migration[8.1]
  def change
    remove_foreign_key :shipments, :couriers, column: :courier_id
    remove_check_constraint :shipments, "weight_grams > 0",
                            name: "shipments_weight_positive"
  end
end

go deeper

for a junior

Say what a foreign key and a check constraint do, and write add_foreign_key :shipments, :couriers from memory.

for a middle

Explain the default names, the on_delete options, what an invalid write raises, and what each remove call must include to stay reversible.

for a senior

Defend constraints alongside validations: list the writers that skip models, and plan how adding a constraint to a populated table avoids a long lock.

for a principal

Set the policy for which rules live in the database and which in models, and how the two are kept from drifting apart.

## Constraints, not model rules Validations and `belongs_to` checks live in Ruby and run only when a record is saved through them. `update_column`, `insert_all`, `upsert_all`, raw SQL and other applications sharing the database skip them. `add_foreign_key` and `add_check_constraint` put the rule **in the database**, where every writer has to pass it. In a courier app: ```ruby class AddShipmentConstraints < ActiveRecord::Migration[8.1] def change add_foreign_key :shipments, :couriers, on_delete: :restrict add_check_constraint :shipments, "weight_grams > 0", name: "shipments_weight_positive" end end ``` ## add_foreign_key `add_foreign_key :shipments, :couriers` assumes the column is the singular of the target table plus `_id` (`courier_id`) and the referenced key is `id`. The useful options: | Option | Default | Purpose | |---|---|---| | `column:` | `courier_id` | a column with another name, e.g. `column: :sender_id` with `:users` | | `primary_key:` | `id` | a different referenced column | | `name:` | `fk_rails_` plus 10 hex characters | an explicit constraint name | | `on_delete:` / `on_update:` | none (the database's own default) | `:cascade`, `:nullify` or `:restrict` | | `if_not_exists:` | `false` | skip if an equal foreign key already exists | The generated name is deterministic: it is derived from the table and column, so the same migration gives the same name on every machine. `db/schema.rb` does not even write names that match `fk_rails_<hash>` (the dumper's `fk_ignore_pattern`), because loading the schema regenerates them. `on_delete: :cascade` deletes shipments when their courier row is deleted, inside the database and without running any model callbacks; `:nullify` sets `courier_id` to NULL; `:restrict` refuses the delete. ## add_check_constraint `add_check_constraint :shipments, "weight_grams > 0"` adds `CHECK (weight_grams > 0)`. The expression is a SQL string, evaluated by the database on each insert and update. Without `name:` the constraint is called `chk_rails_` plus a hash, which, like foreign keys, the schema dumper leaves out. Giving a readable name pays off because the database error message names the constraint. `if_not_exists: true` makes the call skip a constraint that already exists. ## Removing them so rollback still works Both `add_*` calls invert to their `remove_*` counterparts with no extra work. The removals need enough information to rebuild the constraint: - `remove_foreign_key :shipments, :couriers` is reversible: rollback calls `add_foreign_key :shipments, :couriers`. - `remove_foreign_key :shipments, column: :courier_id` drops the right constraint but is **not** reversible: rollback raises `ActiveRecord::IrreversibleMigration` ("remove_foreign_key is only reversible if given a second table"). Pass the table as well: `remove_foreign_key :shipments, :couriers, column: :courier_id`. - `remove_check_constraint :shipments, "weight_grams > 0", name: "shipments_weight_positive"` repeats the expression, so rollback can add the constraint back. A name on its own is enough to drop it, but not to rebuild it. ## What the application sees on a violation A write that breaks a constraint is rejected by the database. Active Record translates the adapter error into an exception: `ActiveRecord::InvalidForeignKey` for a foreign key and `ActiveRecord::CheckViolation` for a check constraint, both subclasses of `ActiveRecord::StatementInvalid`. Because the database raised it, `save` does not return `false` and `errors` stays empty; the exception propagates. That is why teams keep a matching validation for the friendly form message and the constraint as the guarantee. ## Choosing what happens on delete Picking `on_delete:` is a modelling decision, written once in the migration: - **No option** leaves the database default, which refuses to delete a courier that still has shipments. - **`:restrict`** states that refusal explicitly. - **`:nullify`** keeps the shipments and clears their `courier_id`, which only works if the column allows NULL. - **`:cascade`** deletes the shipments together with the courier. The database does it directly, so no model callbacks run and nothing is logged by the app. Foreign keys can also span several columns: `add_foreign_key :orders, :carts, primary_key: [:shop_id, :user_id]` builds a composite key for a table with a composite primary key. ## Where these calls stop - Adding a constraint to a large table that already has data can lock it while the database checks every row. The lock-safe way (adding with `validate: false` and validating later on PostgreSQL) is a separate topic from writing the call. - Both methods do nothing on an adapter that does not support the feature, so check the adapter before relying on one. - Neither call changes the model; `belongs_to` and validations are declared in the model class.

  • What happens when a Rails app saves a shipment that breaks the weight check constraint?
    The database rejects the INSERT or UPDATE, and Active Record raises `ActiveRecord::CheckViolation`, a subclass of `ActiveRecord::StatementInvalid`. `save` does not return `false` and no message lands in `errors`, so a matching model validation is still useful for user-facing feedback.
  • Why does db/schema.rb show add_foreign_key :shipments, :couriers without a name?
    The default name `fk_rails_<10 hex>` is computed from the table and column, so the schema dumper skips names matching that pattern. Loading the schema regenerates the same name. A name you passed with `name:` is written into the dump, because Rails could not regenerate it.

  • add_foreign_key is only Active Record metadata that the database ignores
  • remove_foreign_key :shipments, column: :courier_id rolls back cleanly
  • A check constraint violation makes save return false with an error message
  • db/schema.rb cannot hold foreign keys, so db:schema:load loses them
  • on_delete: :cascade runs the child model's destroy callbacks