In an Active Record model, when do validations run, and how does a failed validation stop a save and report why?
answer
- save calls valid? first
- valid? clears errors, then runs
- context :create or :update
- errors.full_messages, errors[:attr]
- save(validate: false) skips them
basics
~20 ssave, 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 sValidations 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 linesplayer = 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::RecordInvalidgo deeper
Recall that save calls valid? first, returns false on failure and leaves the reasons in errors.full_messages.
Explain the steps of valid?, the create and update contexts, and the errors readers including details for machine-readable output.
Know every write path that skips validations and back the critical rules with database constraints so those paths cannot store bad data.
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.