Active Records implement validation by overwriting Base#validate (or the
variations, validate_on_create and validate_on_update).
Each of these methods can inspect the state of the object, which usually
means ensuring that a number of attributes have a certain value (such as
not empty, within a given range, matching a certain regular expression).
Example:
class Person < ActiveRecord::Base
protected
def validate
errors.add_on_empty %w( first_name last_name )
errors.add("phone_number", "has invalid format") unless phone_number =~ /[0-9]*/
end
def validate_on_create
unless valid_discount?(membership_discount)
errors.add("membership_discount", "has expired")
end
end
def validate_on_update
errors.add_to_base("No changes have occurred") if unchanged_attributes?
end
end
person = Person.new("first_name" => "David", "phone_number" => "what?")
person.save
person.errors.empty?
person.errors.count
person.errors.on "last_name"
person.errors.on "phone_number"
person.errors.each_full { |msg| puts msg }
"Phone number has invalid format"
person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" }
person.save
An Errors object is automatically created for every Active Record.
Please do have a look at ActiveRecord::Validations::ClassMethods for a
higher level of validations.
| Modules |
| ClassMethods |
All of the following validations are defined in the class scope of the
model that you’re interested in validating. They offer a more
declarative way of specifying when the model is valid and when it is not.
It is recommended to use these over the low-level calls to validate and
validate_on_create when possible.
|
| Public Methods |
| errors |
Returns the Errors object that holds all information about attribute error
messages.
|
| included |
|
| save_with_validation |
The validation process on save can be skipped by passing false. The regular
Base#save method is replaced with this when the validations module is mixed
in, which it is by default.
|
| save_with_validation! |
Attempts to save the record just like Base#save but will raise a
RecordInvalid exception instead of returning false if the record is not
valid.
|
| update_attribute_with_validation_skipping |
Updates a single attribute and saves the record without going through the
normal validation procedure. This is especially useful for boolean flags on
existing records. The regular update_attribute method in Base is
replaced with this when the validations module is mixed in, which it is by
default.
|
| valid? |
Runs validate and validate_on_create or validate_on_update and returns true
if no errors were added otherwise false.
|
| Protected Methods |
| validate |
Overwrite this method for validation checks on all saves and use
Errors.add(field, msg) for invalid attributes.
|
| validate_on_create |
Overwrite this method for validation checks used only on creation.
|
| validate_on_update |
Overwrite this method for validation checks used only on updates.
|
<code/>and<pre/>for code samples.