In this conclusion to a five-part series that delves into the Rails framework's Active Record, you'll finish learning about validations, and take a look at callbacks. This article is excerpted from chapter five of the book Beginning Rails: From Novice to Professional, written by Jeffrey Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
Callbacks and the Active Record - Validating the Format of an Attribute (Page 2 of 5 )
Thevalidates_format_ofmethod checks whether a value is in the correct format. Using this method requires familiarity with regular expressions (regex) or being able to steal other people’s regular expressions. The classic example (and the one we need) is email. Add the method shown in Listing 5-23 to ourUser model.
Listing 5-23. validates_format_of Method, in app/models/user.rb
class User < ActiveRecord::Base validates_format_of :email, :with => /^[^@][\w.-]+@[\w.-]+[.][a-z]{2,4}$/i end
Don’t be put off by how complicated this looks. We simply pass in the:withoption and a regex object to say what patterns we want to match.
■Tip If you want to learn more about using regular expressions, you will find many tutorials and books on the subject. One good reference is Regular Expression Recipes (Apress, 2004).
Validating Confirmation
Whenever a user changes an important piece of data (especially the password), you may want the user to confirm that entry by typing it again. This is the purpose of thevalidates_confirmation_ofmethod. When you use this helper, you create a new virtual attribute called#{field_name}_confirmation. Let’s add this to ourUsermodel for password confirmation, as shown in Listing 5-24.
Listing 5-24. validates_confirmation_of Method, in app/models/user.rb
class User < ActiveRecord::Base validates_confirmation_of :password end
Thepassword attribute is a column in theusers table, but thepassword_confirmationattribute is virtual. It exists only as an in-memory variable for validating the password. This check is performed only ifpassword_confirmationis notniland runs whenever the user saves the object.