module ClassMethods
Ruby on Rails 2.3.18
Active Record classes can implement validations in several ways. The highest level, easiest to read, and recommended approach is to use the declarative validates_..._of class methods (and validates_associated) documented below. These are sufficient for most model validations.
Slightly lower level is validates_each. It provides some of the same options as the purely declarative validation methods, but like all the lower-level approaches it requires manually adding to the errors collection when the record is invalid.
At a yet lower level, a model can use the class methods validate, validate_on_create and validate_on_update to add validation methods or blocks. These are ActiveSupport::Callbacks and follow the same rules of inheritance and chaining.
The lowest level style is to define the instance methods validate, validate_on_create and validate_on_update as documented in ActiveRecord::Validations.
validate, validate_on_create and validate_on_update Class Methods
Calls to these methods add a validation method or block to the class. Again, this approach is recommended only when the higher-level methods documented below (validates_..._of and validates_associated) are insufficient to handle the required validation.
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.