validate
- 1.0.0 (0)
- 1.1.6 (0)
- 1.2.6 (0)
- 2.0.3 (38)
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0
- 3.0.9
- 3.1.0
- 3.2.1
- 3.2.8
- 3.2.13
- 4.0.2
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
validate(*methods, &block)
public
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
This usage applies to #validate_on_create and #validate_on_update as well.
Is it really deprecated?
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.
More on deprecation
This is not deprecated. I think the docs are confused because the validate, validate_on_create, and validate_on_update methods are actually callbacks and not explicitly defined on their own. The correct usage is the same as in the docs above.
You can call several times
You can call it several times, like:
class Comment < ActiveRecord::Base validate :must_be_friends validate :must_be_awesome ...
or with several arguments:
class Comment < ActiveRecord::Base validate :must_be_friends, :must_be_awesome ...
You can call it with an { :on => ~~~ } as the last argument
For example:
validate :must_be_friends, :on => :create