| 300 | | |
|---|
| | 300 | # Adds a validation method or block to the class. This is useful when |
|---|
| | 301 | # overriding the #validate instance method becomes too unwieldly and |
|---|
| | 302 | # you're looking for more descriptive declaration of your validations. |
|---|
| | 303 | # |
|---|
| | 304 | # This can be done with a symbol pointing to a method: |
|---|
| | 305 | # |
|---|
| | 306 | # class Comment < ActiveRecord::Base |
|---|
| | 307 | # validate :must_be_friends |
|---|
| | 308 | # |
|---|
| | 309 | # def must_be_friends |
|---|
| | 310 | # errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee) |
|---|
| | 311 | # end |
|---|
| | 312 | # end |
|---|
| | 313 | # |
|---|
| | 314 | # Or with a block which is passed the current record to be validated: |
|---|
| | 315 | # |
|---|
| | 316 | # class Comment < ActiveRecord::Base |
|---|
| | 317 | # validate do |comment| |
|---|
| | 318 | # comment.must_be_friends |
|---|
| | 319 | # end |
|---|
| | 320 | # |
|---|
| | 321 | # def must_be_friends |
|---|
| | 322 | # errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee) |
|---|
| | 323 | # end |
|---|
| | 324 | # end |
|---|
| | 325 | # |
|---|
| | 326 | # This usage applies to #validate_on_create and #validate_on_update as well. |
|---|