instance method
validate
Ruby on Rails 7.2.3
Since v3.0.20Signature
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
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
Or with a block where self points to the current record to be validated:
class Comment include ActiveModel::Validations validate do errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee) end end
Note that the return value of validation methods is not relevant. It’s not possible to halt the validate callback chain.
Options
-
:on- Specifies the contexts where this validation is active. Runs in all validation contexts by defaultnil. You can pass a symbol or an array of symbols. (e.g.on: :createoron: :custom_validation_contextoron: [:create, :custom_validation_context]) -
:if- Specifies a method, proc, or string to call to determine if the validation should occur (e.g.if: :allow_validation, orif: Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to atrueorfalsevalue. -
:unless- Specifies a method, proc, or string to call to determine if the validation should not occur (e.g.unless: :skip_validation, orunless: Proc.new { |user| user.signup_step <= 2 }). The method, proc, or string should return or evaluate to atrueorfalsevalue.
NOTE: Calling validate multiple times on the same method will overwrite previous definitions.
Parameters
-
argsrest -
blockblock
Source
# File activemodel/lib/active_model/validations.rb, line 173
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.merge(if: [predicate_for_validation_context(options[:on]), *options[:if]])
end
set_callback(:validate, *args, options, &block)
end
Defined in activemodel/lib/active_model/validations.rb line 173
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActiveModel::Validations::ClassMethods