instance method validates_each

Ruby on Rails 2.3.18

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

validates_each(*attrs)

Adds a validation method or block to the class. This is useful when overriding the validate instance method becomes too unwieldly and you’re looking for more descriptive declaration of your validations.

This can be done with a symbol pointing to a method:

class Comment < ActiveRecord::Base
  validate :must_be_friends

  def must_be_friends
    errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
  end
end

Or with a block which is passed the current record to be validated:

class Comment < ActiveRecord::Base
  validate do |comment|
    comment.must_be_friends
  end

  def must_be_friends
    errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
  end
end

This usage applies to validate_on_create and +validate_on_update as well+.

Validates each attribute against a block.

class Person < ActiveRecord::Base
  validates_each :first_name, :last_name do |record, attr, value|
    record.errors.add attr, 'starts with z.' if value[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.

  • :allow_blank - Skip validation if attribute is blank.

  • :if - Specifies a method, proc or string to call to determine if the validation should occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to a true or false value.

  • :unless - Specifies a method, proc or string to call to determine if the validation should not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The method, proc or string should return or evaluate to a true or false value.

Parameters

attrs rest
Source
# File activemodel/lib/active_model/validations.rb, line 60
      def validates_each(*attrs)
        options = attrs.extract_options!.symbolize_keys
        attrs   = attrs.flatten

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

Defined in activemodel/lib/active_model/validations.rb line 60 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveModel::Validations::ClassMethods

Type at least 2 characters to search.

↑↓ navigate · open · esc close