In an Active Record model, how do on: :create, a custom context like on: :registration, and if: control when a validation runs?
answer
- default context: :create or :update
- no on: means every context
- custom context only when passed
- save(context: :registration)
- if:/unless: take symbols or lambdas
basics
~20 son: limits a validation to a context: :create for new records, :update for persisted ones, or a custom name passed as valid?(:registration) or save(context: :registration). if: and unless: add a runtime condition from a method name or lambda.
solid answer
~40 sEvery validation run has a context. `save` uses `:create` for a new record and `:update` for a persisted one, so `on: :create` runs only on the first save. A custom context such as `on: :registration` runs only when you ask for it: `player.valid?(:registration)` or `player.save(context: :registration)`. Validations **without** `on:` run in every context, but an explicit context replaces the default one, so `save(context: :registration)` does **not** run `on: :create` rules unless you pass `context: [:create, :registration]`. `if:` and `unless:` take a method name, a lambda or an array of them and are evaluated per run: `validates :guardian_email, presence: true, if: :minor?`. Group several rules sharing a condition with `with_options if: :minor? do ... end`.
code
ruby · 13 linesclass Player < ApplicationRecord
validates :username, presence: true # every context
validates :code_of_conduct_accepted, acceptance: true, on: :create
validates :guardian_phone, presence: true, on: :registration
validates :guardian_email, presence: true, if: :minor?
def minor? = age.present? && age < 18
end
player = Player.new(username: "coachamy", age: 12)
player.save(context: :registration) # runs username, guardian_phone, guardian_email
# skips the on: :create acceptance rule
player.save(context: [:create, :registration]) # runs all fourgo deeper
Recall that on: :create and on: :update limit a validation to new or persisted records.
Explain custom contexts, how to trigger them with valid? and save(context:), and how if: and unless: are evaluated.
Know that an explicit context replaces the default, and choose contexts for operations and conditions for data so rules cannot be skipped by accident.
Judge when multi-step flows deserve separate form or service objects instead of an ever-growing set of contexts on one model.
## Contexts: which validations apply to this run The league's sign-up flow has a step where a parent completes registration, and some rules apply only there. Rails models this with **validation contexts**: | How validation is triggered | Context | Runs validations with | |---|---|---| | `player.save` on a new record | `:create` | no `on:`, or `on: :create` | | `player.save` on a persisted record | `:update` | no `on:`, or `on: :update` | | `player.valid?(:registration)` | `:registration` | no `on:`, or `on: :registration` | | `player.save(context: :registration)` | `:registration` | no `on:`, or `on: :registration` | | `player.valid?([:create, :registration])` | both | no `on:`, `on: :create` or `on: :registration` | Two rules follow from the table: 1. A validation **without** `on:` runs in every context. 2. An explicit context **replaces** the default. `save(context: :registration)` on a new player does not run `on: :create` validations; pass an array if both sets must run. `on:` itself accepts a symbol or an array: `on: [:create, :registration]`. ## Typical uses of on: - **`on: :create`** for rules that only make sense once, such as accepting the league's code of conduct at sign-up. - **`on: :update`** for rules that need a persisted record, such as checks against existing associated rows. - **Custom contexts** for multi-step flows: `validates :guardian_phone, presence: true, on: :registration` lets a draft player save early and enforces the rule when the parent finalizes. ## if: and unless: Conditions decide **at run time**, per record: ```ruby validates :guardian_email, presence: true, if: :minor? validates :jersey_size, inclusion: { in: %w[YS YM YL S M L] }, unless: -> { jersey_size.nil? } ``` - A **symbol** names an instance method. - A **lambda** is evaluated on the record (with no argument it runs via `instance_exec`, so `jersey_size` refers to the record's attribute). - An **array** requires all of its conditions to hold. - `if:` and `unless:` can be combined on one declaration. When several validations share a condition, `with_options` avoids repeating it: ```ruby with_options if: :minor? do validates :guardian_email, presence: true validates :guardian_phone, presence: true end ``` ## Context or condition? | Question | Use | |---|---| | Does the rule depend on **which operation** is running (create, update, a named step)? | `on:` | | Does it depend on **the record's data** (a minor, a paid plan)? | `if:` / `unless:` | Mixing them up produces subtle bugs. An `if: :new_record?` condition looks like `on: :create`, but it is evaluated from the record's state and ignores explicit contexts; `on: :registration` used to mean "is a minor" forces every caller to remember to pass the context. ## Pitfalls - **Forgotten context.** A custom-context rule silently never runs if no code path passes the context. Test the path that should trigger it. - **Overriding the default.** `save(context: :registration)` skips `on: :create` rules unless you include `:create`. - **Uniqueness with `on: :create`.** Limiting a uniqueness rule to create lets an update rename a player to a taken username; the unique index still has to catch it. - **Conditions with side effects.** `if:` methods can run on every `valid?` call; keep them pure and cheap. ## Testing contexts and conditions Each context and each condition is a branch, and untested branches are where rules silently stop running: 1. Assert a plain `valid?` ignores the `:registration` rule. 2. Assert `valid?(:registration)` enforces it. 3. Assert the `if: :minor?` rule fires for a 12-year-old and not for a 19-year-old. If the registration controller is the only caller passing the context, a request test on that controller is what proves the rule is actually triggered in production code.
- A new player is saved with save(context: :registration). Does validates :code_of_conduct_accepted, acceptance: true, on: :create run?No. The explicit context replaces the default `:create`, so only validations without `on:` and those for `:registration` run. Pass `context: [:create, :registration]` to run both sets.
- What does with_options if: :minor? do around a block of validates calls?It merges `if: :minor?` into every declaration inside the block, so each guardian rule runs only for minors without repeating the condition on each line.
- Saying a validation with on: :registration also runs on a plain save.
- Expecting save(context: :registration) to run on: :create validations as well.
- Using on: :create to express a rule that depends on the record's data.
- Believing validations without on: are skipped when a custom context is passed.
- Putting slow queries or side effects in an if: condition.