skip to content

Validators & Error Objects

Validations gate a save through validates rules, custom validate methods and validator classes, reporting via the errors object. Interviewers ask why a uniqueness check still lets duplicates in.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In an Active Record model, when do validations run, and how does a failed validation stop a save and report why?

level: juniorimportance: must knowfreq 82%

answer

  1. save calls valid? first
  2. valid? clears errors, then runs
  3. context :create or :update
  4. errors.full_messages, errors[:attr]
  5. save(validate: false) skips them

basics

~20 s

save, save!, create, update and their bang forms call valid? before writing; valid? clears errors, runs every validation for the :create or :update context, and any error stops the write, with the reasons left in record.errors.

solid answer

~40 s

Validations run when you call `valid?` (or `invalid?`) and automatically before `save`, `create` and `update` and their bang versions. `valid?` empties `errors`, sets the context to `:create` for a new record or `:update` for a persisted one, runs every validation that applies, and returns `true` only if `errors` is still empty. If it is not, `save` returns `false` without any SQL and `save!` raises `ActiveRecord::RecordInvalid`. The reasons live on the record: `player.errors.full_messages` gives sentences like "Username can't be blank", `player.errors[:username]` gives that attribute's messages, and `errors.details` gives symbols such as `:blank` for code to branch on. `save(validate: false)` skips validations, and calls that bypass the save path (`update_column`, `update_all`, `insert_all`) never run them.

code

ruby · 9 lines
ruby
player = Player.new(username: "", age: 21)
player.valid?              # => false
player.errors.full_messages
# => ["Username can't be blank", "Username is too short (minimum is 3 characters)",
#     "Age must be in 6..18"]
player.errors[:age]        # => ["must be in 6..18"]
player.errors.details[:username].first # => {error: :blank}
player.save                # => false, no INSERT sent
player.save!               # => ActiveRecord::RecordInvalid

go deeper

for a junior

Recall that save calls valid? first, returns false on failure and leaves the reasons in errors.full_messages.

for a middle

Explain the steps of valid?, the create and update contexts, and the errors readers including details for machine-readable output.

for a senior

Know every write path that skips validations and back the critical rules with database constraints so those paths cannot store bad data.

for a principal

Decide which rules belong in model validations, which in the database and which in service code, and keep them consistent.

## Where validations sit in a save In the youth-sports league app, a `Player` must have a username and an age. The model declares the rules once: ```ruby class Player < ApplicationRecord validates :username, presence: true, length: { in: 3..20 } validates :age, numericality: { only_integer: true, in: 6..18 } end ``` Active Record runs those rules **before** it writes. `save` (and therefore `create` and `update`) first calls `valid?`; only if that returns `true` does the INSERT or UPDATE happen. ## What valid? does, step by step 1. **Clears `errors`.** Every run starts from an empty list, so stale messages from an earlier attempt disappear. 2. **Picks a context.** With no argument, the context is `:create` for a new record and `:update` for a persisted one. Validations declared with `on:` run only in their context; validations without `on:` run in every context. 3. **Runs the validations** in the order they were declared: `validates` rules, `validate :method` checks and `validates_with` classes all add to the same `errors` object. 4. **Returns** `true` when `errors` is empty, `false` otherwise. `invalid?` is the negation. Calling `valid?` yourself is a cheap way to check a record without saving it, for example before showing a confirmation step. ## What the failure looks like | Call | Validation fails | |---|---| | `player.save` | returns `false`; no SQL sent | | `player.save!` | raises `ActiveRecord::RecordInvalid` | | `Player.create(attrs)` | returns the unsaved player | | `player.update(attrs)` | returns `false` | | `player.valid?` | returns `false`; nothing is saved either way | In every case the reasons are on `player.errors`. ## Reading the errors object `errors` is an `ActiveModel::Errors` collection of `ActiveModel::Error` objects. The common readers: - `errors.full_messages`: `["Username can't be blank", "Age must be less than or equal to 18"]`, attribute name included; - `errors[:username]`: just that attribute's messages, `["can't be blank"]`; - `errors.full_messages_for(:age)`: full sentences for one attribute; - `errors.details`: `{ username: [{ error: :blank }], age: [{ error: :less_than_or_equal_to, count: 18 }] }`, the machine-readable form an API should send; - `errors.of_kind?(:username, :blank)`: a boolean check by error type; - `errors.any?` / `errors.empty?` / `errors.count`. Messages come from locale files, so `"can't be blank"` is a default text that translations can replace; the `:blank` **type** is what code should test. ## What does not run validations - `save(validate: false)` and `save!(validate: false)`, deliberately; - writes that skip the save path entirely: `update_column(s)`, `update_all`, `insert_all` / `upsert_all` and `delete`. Those calls are where invalid data usually enters a table, which is one reason database constraints still matter alongside model validations. ## What validations are not - They are **not** a security boundary on their own: they check the record's state, not who is allowed to change it. - They are **not** atomic with the write: a check that queries the database (uniqueness) can be outdated a millisecond later. - They are **not** run on read: invalid rows already in the table load fine and fail only on their next save. ## Checking a record without saving Three calls run validations without writing anything: 1. `player.valid?` returns a boolean and fills `errors`. 2. `player.invalid?` returns the opposite boolean and fills `errors` the same way. 3. `player.validate!` raises `ActiveRecord::RecordInvalid` when the record is invalid, which suits scripts and jobs that prefer exceptions. All three accept a context argument, such as `player.valid?(:registration)`, to run validations declared for that context. A useful habit in the console and in tests is `player.valid?` followed by `player.errors.details`: it shows exactly which rule failed, by type, without parsing English messages.

  • You call errors.add(:base, "Roster is full") in the controller and then call valid?. Why is the message gone?
    `valid?` starts by clearing `errors` and then rebuilds it from the model's validations. A message added from outside is wiped. Put the rule in a `validate` method on the model so it is added during every run.
  • Why should an API return errors.details rather than full_messages?
    `details` gives stable symbols such as `:blank` or `:taken` with their options, which clients can map to their own text. `full_messages` are locale-dependent sentences that change with translations, so clients cannot reliably branch on them.

  • Saying validations run when the record is loaded from the database.
  • Expecting update_column to run the model's validations before writing.
  • Adding errors from a controller and expecting them to survive valid?.
  • Checking error message strings in code instead of error types.
  • Believing save sends the INSERT and rolls it back when validation fails.
open as a page

Why can validates :username, uniqueness: true still let two players register the same username, and how do you close the gap in a Rails app?

level: seniorimportance: must knowfreq 65%

basics

~20 s

The validator runs a SELECT and the save runs a later INSERT, so two concurrent requests can both find no row and both insert. A unique index makes the second INSERT fail with ActiveRecord::RecordNotUnique, which the app rescues into a :taken error.

open as a page

In a Rails youth-sports Player model, which built-in validators enforce a username format and an age from 6 to 18, and what traps hide in them?

level: middleimportance: should knowfreq 55%

basics

~20 s

Use format: { with: /\A[a-z0-9_]+\z/ } and length: { in: 3..20 } for the username, numericality: { only_integer: true, in: 6..18 } for age, and comparison: for dates; ^ or $ in a format regex raises, and presence rejects false.

open as a page

In Rails, when do you write validate :method, a validates_with validator class or an ActiveModel::EachValidator, and how does each add errors?

level: middleimportance: should knowfreq 50%

basics

~20 s

Use validate :method for a rule specific to one model, an ActiveModel::EachValidator for a per-attribute rule reused through validates :attr, name: true, and an ActiveModel::Validator with validates_with for whole-record rules; all add messages with record.errors.add.

open as a page

In an Active Record model, how do on: :create, a custom context like on: :registration, and if: control when a validation runs?

level: middleimportance: should knowfreq 42%

basics

~20 s

on: 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.

open as a page

In Active Record, what do scope: and case_sensitive: change in validates :username, uniqueness:, and what query does the check run?

level: middleimportance: should knowfreq 60%

basics

~20 s

uniqueness runs SELECT 1 ... LIMIT 1 for another row with the same value (excluding the record itself); scope: adds equality conditions on other columns, and case_sensitive: false compares with LOWER() instead of the column's collation.

open as a page