Ruby, Ruby on Rails

Tuesday, December 11, 2007

Ruby on Rails - script/console

A nice and easy way to check you validation rules...

With a table called users with fields user_name, password, and email, we can add simple validation to the model User.


validates_uniqueness_of :user_name, :email
validates_length_of :user_name, :within => 4..20
validates_length_of :password, :within => 4..20
validates_length_of :email, :maximum => 50
validates_format_of :user_name,
:with => /^[A-Z0-9_]*$/i,
:message => "must contain only letters, " +
"numbers and underscores"
validates_format_of :email,
:with => /@/,
:message => "must be a valid email address"



Then using script/console, we can check our validation:

First, try to add a bad record:


$ script/console
Loading development environment.
>> user = User.new(:user_name => "pooh bear",
?> :password => "pb",
?> :email => "poohbear_at_100akerwood.com")
=> #"pooh bear", "password"=>"pb", "email"=>"poohbear_at_100akerwood.com"}>
>> user.save
=> false


Then you can inspect the errors individually with errors.on method:

>> user.errors.on(:user_name)
=> "must contain only letters, numbers and underscores"
>> user.errors.on(:password)
=> "is too short (minimum is 4 characters)"
>> user.errors.on(:email)
=> "must be a valid email address"


or all at once with errors.full_messages method:

>> user.errors.full_messages
=> ["Screen name must contain only letters, numbers and underscores", "Password is too short (minimum is 4 characters)", "Email must be a valid email address"]
>>

No comments:

About Me

My photo
Developer (Ruby on Rails, iOS), musician/composer, Buddhist, HSP, Vegan, Aspie.