O'Reilly logo

Ruby on Rails® for Microsoft Developers by Antonio Cangiano

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.6. ActiveRecord Validations

Validations are a feature that enables you to specify certain rules before a record is created or updated in the database. Several high-level helpers are provided for the most common tasks, but it's good to know the three generic validation methods that allow you to perform validations based on a method that you've defined. These are validate, validate_on_create, and validate_on_update.

When you define a validation rule with validate, ActiveRecord applies that rule to determine whether or not the object should be saved. If the object fails the validation, it's not saved and an error message is added to it so that, in the context of Rails, the view can display it to the user again, who can correct the error by changing the data in the form and trying to resubmit it.

validate_on_create is similar to validate, but it's triggered only when a new record is being created, not when this is being updated. Vice versa, validate_on_update validates attempts to update a record, but not the creation of new ones. The method valid? can also be used to trigger all the existing validations defined for a model object.

Because the method save is used for both the creation and the update of a record, how does ActiveRecord know which of the two operations it needs to perform? The answer is that it uses the new_record? method, which returns true if it's a new record (wherein an INSERT is performed), or false, in which case an UPDATE statement is issued,

You'll also notice ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required