Home
Ruby on Rails
Models
You can create your own validations by implementing the validate method (or the variations, validate_on_create and validate_on_update) in your model. The validate method will be called by ActiveRecord before every save or update, whilst the validate_on_create and validate_on_update methods will only be called when saving new records or updating existing records respectively. Most validation methods simply do two things:
Each ActiveRecord object has its own errors object which stores a list of errors related to that object and is accessible via the errors method on the object.
The errors object itself has a number of methods which enable you to both add to the list of errors, or inspect the object for errors which have already been added. For example, to add an error to the name attribute of an object, we would use the add method...
object.errors.add(:name, "shouldn't be empty!")
...and to retrieve errors on the :name attribute we could read from the errors object...
object.errors.on(:name) # => "shouldn't be empty!"
You will find our cheatsheet ActiveRecord Validation Errors a useful resource for manipulating the errors object.
Here are some examples of implementing low-level, roll-your-own validation methods...
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 # is only run the first time a new object is saved 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 # => false (and doesn't do the save) person.errors.empty? # => false person.errors.count # => 2 person.errors.on "last_name" # => "can't be empty" person.errors.on "phone_number" # => "has invalid format" person.errors.each_full { |msg| puts msg } # => "Last name can't be empty\n" + "Phone number has invalid format" person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" } person.save # => true (and person is now saved in the database)
Each ActiveRecord backed model in Rails has an errors object which errors are added to if the model fails validation. This cheatsheet covers methods available, default errors messages and view error helpers.
More