instance method validate

Ruby on Rails 3.0.20

Since v3.0.20

Available in: 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

validate(*args, &block)

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

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

class Comment
  include ActiveModel::Validations

  validate :must_be_friends

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

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

class Comment
  include ActiveModel::Validations

  validate do |comment|
    comment.must_be_friends
  end

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

Parameters

args rest
block block
Source
# File activemodel/lib/active_model/validations.rb, line 121
      def validate(*args, &block)
        options = args.extract_options!
        if options.key?(:on)
          options = options.dup
          options[:if] = Array.wrap(options[:if])
          options[:if] << "validation_context == :#{options[:on]}"
        end
        args << options
        set_callback(:validate, *args, &block)
      end

Defined in activemodel/lib/active_model/validations.rb line 121 · 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