Method: ActiveRecord::Validations::ClassMethods#validates_each

Defined in:
lib/active_record/validations.rb

#validates_each(*attrs) ⇒ Object

Validates each attribute against a block.

class Person < ActiveRecord::Base
  validates_each :first_name, :last_name do |record, attr|
    record.errors.add attr, 'starts with z.' if attr[0] == ?z
  end
end

Options:

  • on - Specifies when this validation is active (default is :save, other options :create, :update)

  • allow_nil - Skip validation if attribute is nil.



240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/active_record/validations.rb', line 240

def validates_each(*attrs)
  options = attrs.last.is_a?(Hash) ? attrs.pop.symbolize_keys : {}
  attrs = attrs.flatten

  # Declare the validation.
  send(validation_method(options[:on] || :save)) do |record|
    attrs.each do |attr|
      value = record.send(attr)
      next if value.nil? && options[:allow_nil]
      yield record, attr, value
    end
  end
end