You are here: Home Solidarrow Ruby on Rails Solidarrow Models

* ActiveRecord Validations Cheatsheet

Comprehensive but concise details of Rails' built-in class validation helper methods from validates_acceptance_of through to validates_uniqueness_of, along with details of how to roll your own low-level validations along with examples...

Low level validations

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:

  • Inspect the attributes of an object and check whether their values pass one or more conditions (such as making sure a name attribute is not empty and/or that it matches a certain regular expression)
  • If an attribute's value does not pass, add an error message to it

Errors

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...

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 # 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)




 

 

> RELATED ARTICLE

* Active Record Validation Errors Cheatsheet

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