module ActiveModel::Validations::ClassMethods
def validate(*args, &block)
NOTE: Calling +validate+ multiple times on the same method will overwrite previous definitions.
value.
method, proc, or string should return or evaluate to a +true+ or +false+
or unless: Proc.new { |user| user.signup_step <= 2 }). The
determine if the validation should not occur (e.g. unless: :skip_validation,
* :unless - Specifies a method, proc, or string to call to
proc or string should return or evaluate to a +true+ or +false+ value.
or if: Proc.new { |user| user.signup_step > 2 }). The method,
if the validation should occur (e.g. if: :allow_validation,
* :if - Specifies a method, proc, or string to call to determine
on: [:create, :custom_validation_context])
on: :custom_validation_context or
or an array of symbols. (e.g. on: :create or
Runs in all validation contexts by default +nil+. You can pass a symbol
* :on - Specifies the contexts where this validation is active.
Options:
It's not possible to halt the validate callback chain.
Note that the return value of validation methods is not relevant.
end
end
errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
validate do
include ActiveModel::Validations
class Comment
Or with a block where +self+ points to the current record to be validated:
end
end
errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
def must_be_friends
end
comment.must_be_friends
validate do |comment|
include ActiveModel::Validations
class Comment
With a block which is passed with the current record to be validated:
end
end
errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee)
def must_be_friends
validate :must_be_friends
include ActiveModel::Validations
class Comment
This can be done with a symbol pointing to a method:
you're looking for more descriptive declaration of your validations.
overriding the +validate+ instance method becomes too unwieldy and
Adds a validation method or block to the class. This is useful when
def validate(*args, &block) options = args.extract_options! if args.all?(Symbol) options.each_key do |k| unless VALID_OPTIONS_FOR_VALIDATE.include?(k) raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{VALID_OPTIONS_FOR_VALIDATE.map(&:inspect).join(', ')}. Perhaps you meant to call `validates` instead of `validate`?") end end end if options.key?(:on) options = options.dup options[:on] = Array(options[:on]) options[:if] = [ ->(o) { !(options[:on] & Array(o.validation_context)).empty? }, *options[:if] ] end set_callback(:validate, *args, options, &block) end