Callbacks and the Active Record
(Page 1 of 5 )
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).
Validating the Length or Size
Sometimes you want to validate the length, or size, of a field entry. You can do this by using thevalidates_length_ofmethod. We’ll use this method in ourUsermodel to specify a valid range of characters for a login name, as shown in Listing 5-22. The option for specifying a range of values is:within.
Listing 5-22. validates_length_of Method, in app/models/user.rb
class User < ActiveRecord::Base
validates_length_of :login, :within => 4..40
end
If you want to ensure only the minimum or maximum, you can use the:minimumor:maximumattributes. Table 5-7 lists thevalidates_length_ofmethod options.
Table 5-7. Options for validates_length_of
Option | Description |
:minimum | Specifies the minimum size of the attribute |
:maximum | Specifies the maximum size of the attribute |
:is | Specifies the exact size of the attribute |
:within | Specifies the valid range (as a Ruby Range object) of values acceptable for the attribute |
:allow_nil | Specifies that the attribute may be nil; if so, the validation will be skipped. |
:too_long | Specifies the error message to add if the attribute exceeds the maximum. |
:too_short | Specifies the error message to add if the attribute is below the minimum. |
:wrong_length | Specifies the error message to add if the attribute is of the wrong size |
:message | Specifies the error message to add if :minimum, :maximum, or :is is violated. |
Next: Validating the Format of an Attribute >>
More Ruby-on-Rails Articles
More By Apress Publishing