skip to content

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%

answer

  1. validate :method for one model's rule
  2. EachValidator: validate_each(record, attr, value)
  3. validates :x, age_bracket: true lookup
  4. Validator#validate(record) for whole-record rules
  5. one validator instance per declaration

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.

solid answer

~40 s

A rule that only one model needs goes in a private method registered with `validate :age_fits_division`, which calls `errors.add(:birth_date, :outside_division, division: division.name)` when it fails. A per-attribute rule you want to reuse becomes an `ActiveModel::EachValidator`: `class AgeBracketValidator < ActiveModel::EachValidator` implements `validate_each(record, attribute, value)`, and `validates :birth_date, age_bracket: { min: 6, max: 18 }` finds it by name (`age_bracket` becomes `AgeBracketValidator`), with options available as `options` and `allow_nil`/`if:` handled for free. A rule about the whole record goes in an `ActiveModel::Validator` subclass implementing `validate(record)`, attached with `validates_with RosterSizeValidator`. Validator objects are built once when the class is defined and shared by every record, so they must not keep per-record state in instance variables.

code

ruby · 13 lines
ruby
class Player < ApplicationRecord
  validates :birth_date, age_bracket: { min: 6, max: 18 }
  validate :age_fits_division
end

class Coach < ApplicationRecord
  validates :birth_date, age_bracket: { min: 18, max: 80 }, allow_nil: true
end

Team.validates_with RosterSizeValidator

player.valid?
player.errors.details[:birth_date] # => [{error: :age_bracket, min: 6, max: 18}]

go deeper

for a junior

Recall that validate :method_name runs a model method that adds to errors when a rule fails.

for a middle

Explain when to extract an EachValidator or a Validator class, how validates finds a validator by name and how options reach it.

for a senior

Design reusable validators with error types and interpolation values, and avoid shared-instance state across records and threads.

for a principal

Decide which business rules belong in validators at all versus service objects that know the use case and its context.

## Three ways to write a rule Rails does not ship The league needs rules no built-in validator expresses: a player's birth date must fit the division's age bracket, and a team cannot exceed its roster limit. Rails offers three places to put such logic, all of which feed the same `errors` object. | Tool | Declared with | You implement | Best for | |---|---|---|---| | validation method | `validate :method_name` | an instance method | a rule one model needs | | `ActiveModel::EachValidator` | `validates :attr, name: options` | `validate_each(record, attribute, value)` | a per-attribute rule reused across models | | `ActiveModel::Validator` | `validates_with ClassName, options` | `validate(record)` | a whole-record rule, or one needing several attributes | ## validate :method ```ruby class Player < ApplicationRecord validate :age_fits_division private def age_fits_division return if birth_date.blank? || division.nil? unless division.birth_dates.cover?(birth_date) errors.add(:birth_date, :outside_division, division: division.name) end end end ``` Note the singular `validate`: it registers a method (or block). The method signals failure **only** by adding to `errors`; its return value is ignored. `validate` accepts `on:`, `if:` and `unless:` like `validates`. ## ActiveModel::EachValidator When the same rule appears on several models (a coach's and a player's birth date), extract it: ```ruby # app/validators/age_bracket_validator.rb class AgeBracketValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) age = value && ((Date.current - value) / 365.25).floor return if age && age.between?(options[:min], options[:max]) record.errors.add(attribute, options[:message] || :age_bracket, **options.slice(:min, :max)) end end ``` - `validates :birth_date, age_bracket: { min: 6, max: 18 }` looks up the constant `AgeBracketValidator` from the key; an unknown key raises `ArgumentError` ("Unknown validator"). - The `validate` method that `EachValidator` provides already applies `allow_nil:` and `allow_blank:` before calling `validate_each`; `if:`, `unless:` and `on:` are handled by the declaration. - `options` holds the hash you passed; override `check_validity!` to reject bad options when the class loads. ## ActiveModel::Validator with validates_with A rule about the record as a whole, for example a team's roster limit, does not belong to one attribute: ```ruby class RosterSizeValidator < ActiveModel::Validator def validate(record) if record.players.size > record.division.max_roster record.errors.add(:base, :roster_full, max: record.division.max_roster) end end end class Team < ApplicationRecord validates_with RosterSizeValidator end ``` `validates_with` has no default message: the validator must add its own errors. Extra options passed to `validates_with` arrive in `options`. ## Adding errors well 1. **Use a symbol type**, `errors.add(:birth_date, :outside_division)`, not only a string. The type is what `errors.details` reports and what translations key on. 2. **Pass interpolation values** (`division:`, `max:`) so translated messages can use them. 3. **Use `:base`** for errors that do not belong to one field; forms show them at the top. 4. **Do not raise** from a validator for invalid input; add an error and let `valid?` return `false`. (`strict: true` on a declaration raises `ActiveModel::StrictValidationFailed`, which is for programmer errors, not user input.) ## The shared-instance trap Rails builds each validator **once**, when the class body declares it, and reuses that object for every record and every thread. Storing anything per record in an instance variable (`@age = ...`) leaks values between validations and requests. Keep per-record values in local variables, and treat `options` as read-only. ## Where validator classes live and how to test them - Put shared validators in `app/validators/`; every directory under `app/` is autoloaded, so `AgeBracketValidator` resolves with no `require`. - A validator used by one model can sit in that model's file, but extracting it as soon as a second model needs it keeps the rule in one place. - Test an `EachValidator` through a tiny model that includes `ActiveModel::Validations`, declares the rule and calls `valid?`, so the test exercises the same lookup and options handling as production. - Assert on `errors.details` or `errors.of_kind?` rather than on message strings, so a translation change does not break the test.

  • A custom validation method returns false when the rule fails. Why does the record still save?
    Rails ignores the return value of methods registered with `validate`. A record is invalid only when `errors` is non-empty after the run, so the method must call `errors.add(...)`.
  • Why must an EachValidator not cache values in instance variables?
    Rails instantiates each validator once, when the model class declares it, and reuses it for every record and thread. Instance variables therefore persist across validations and can leak one record's value into another's check. Use locals and read-only `options`.

  • Writing validates :age_fits_division instead of validate :age_fits_division for a method.
  • Returning false from a validate method and expecting the save to stop.
  • Storing per-record state in an EachValidator's instance variables.
  • Raising an exception from a validator for ordinary invalid input.
  • Expecting validates_with to add a default message when the validator adds none.