I am a Objective-c programmer so I am not used to having code outside of methods.
I have a two-part question about Rail’s validates.
Consider this code:
class User < ActiveRecord::Base
attr_accessible :name, :email
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 50}
validates :email, :presence => true,
:format => { :with => email_regex }.
:uniqueness => true
end
- When exactly is the
validatesmethod executed? Upon instantiating aUserinstance or when its class definition is loaded? - When does the
Useractually get validated? When I save theUserinstance or create it?
All of the calls within the class definition are called when the class definition is executed, not when an instance is created. It is worth mentioning that the variable email_regex is not a instance variable, but rather a local variable to the class definition.