Ruby on Rails
UnderstandingValidation

Rails has a number of methods and different approaches to facilitate Validations of your ActiveRecord model.

Overview

Why validate?

Validation is a useful tool to ensure the integrity of information in the database. It forms a minimum standard that all records must meet before they can be saved.

Example: pseudo-code

A valid user:
- has a name and password
- has a unique name
- has a password that is between 5 and 15 characters long

With those rules (except written in real Ruby) as part of your model, Rails will not save any user that doesn’t meet the requirements.

When using validation, Rails keeps track of any validation errors and will build error messages for those errors. It is then useful to display these messages back to the user so the errors may be corrected.

When does validation take place?

Validation takes place before a model is saved. If the model being saved doesn’t meet its validation requirements, it will NOT be saved to the database. Attempts to save an invalid model return false. This allows for the “if-save” convention:

if @user.save
  # user was valid and saved
  ..
else
  # user was invalid, not saved
  ..
end

You can trigger validation manually by calling the models validate method.

@user.validate

But likely more useful would be to call valid?, which runs validate then returns true or false.

if @user.valid?
...

Avoiding validation

You can skip validation by passing false to save.

@user.save(false)

The method update_attribute does not trigger validation, and as such, methods that call update_attributes (toggle!, increment! and decrement!) do not trigger validation either.

Skipping validation may result (obviously) in invalid data being recorded to the database.

note: In Rails 1.1.2(ActiveRecord 1.14.2), update_attributes seems to trigger validation. Have not verified if other versions have the same behavior.

What happens when a model is validated?

When a model is validated, any validation errors will be collected in the models errors object.

(expand)

Different Approaches

Declarative vs. overriding #validate, #validate_on_create or #validate_on_update.

(expand)

More information

Advanced topics

category: Understanding, Stub