Skip to Content
Ruby on Rails® for Microsoft Developers
book

Ruby on Rails® for Microsoft Developers

by Antonio Cangiano
April 2009
Intermediate to advanced content levelIntermediate to advanced
479 pages
12h 55m
English
Wrox
Content preview from Ruby on Rails® for Microsoft Developers

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Michael Hartl

Publisher Resources

ISBN: 9780470374955Purchase book