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
# File activerecord/lib/active_record/validations.rb, line 327 def validate(*methods, &block) methods << block if block_given? write_inheritable_set(:validate, methods) end
I think the deprecation notice is in the wrong place, it is actually the instance method ActiveRecord::Validations#validate that has been deprecated.
The same applies to ActiveRecord::Validations#validate_on_create and ActiveRecord::Validations#validate_on_update: they have both been deprecated in favour of the class methods validate_on_create and validate_on_update.
validate :must_be_friends, :on => :create