Agile Web Development with Rails

Page 1

VALIDATION validates_confirmation_of Validates that a field and its doppelgänger have the same content. validates_confirmation_of attr... [ options... ] Many forms require a user to enter some piece of information twice, the second copy acting as a confirmation that the first was not mistyped. If you use the naming convention that the second field has the name of the attribute with _confirmation appended, you can use validates_confirmation_of to check that the two fields have the same value. The second field need not be stored in the database. For example, a view might contain the following: <%= password_field "user" , "password" %><br /> <%= password_field "user" , "password_confirmation" %><br />

Within the User model, you can validate that the two passwords are the same using this: class User < ActiveRecord::Base validates_confirmation_of :password end Options: :if

code

See discussion on page 406.

:unless

code

See discussion on page 406.

:message

text

Default is “doesn’t match confirmation.” :save, :create, or :update.

:on

validates_each Validates one or more attributes using a block. validates_each attr... [ options... ] { |model, attr, value| ... } Invokes the block for each attribute (skipping those that are nil if :allow_nil is true). Passes in the model being validated, the name of the attribute, and the attribute’s value. As the following example shows, the block should add to the model’s error list if a validation fails: class User < ActiveRecord::Base validates_each :name, :email do |model, attr, value| if value =~ /groucho|harpo|chico/i model.errors.add(attr, "You can't be serious, #{value}" ) end end end Options: :allow_nil

boolean

If :allow_nil is true, attributes with values of nil will not be passed into the block. By default they will.

:if

code

See discussion on page 406.

:unless

code

See discussion on page 406.

:on

:save, :create, or :update.

Report erratum

Prepared exclusively for Bill Trammel

this copy is (P1.0 printing, March 2009)

401


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.