`
hot88zh
  • 浏览: 178501 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Active Record Validations and Callbacks

阅读更多

有许多种在保存数据到数据库之前验证数据有效性的方法,包括数据库原生的约束(constraints)、客户端的验证、Controller级别的验证以及Model级别的验证。

数据库约束:
数据库约束和存储过程使得验证机制依赖于数据库本身,会让测试和维护更加困难。但是如果你的数据库会被其它的应用程序所使用,这时候使用一些数据 库级别的约束(constraints)会是个好主意。另外,数据库级别的验证可以安全的处理一些很难用其它方式实现的事件(比如大量使用的表的唯一性 (uniqueness in heavily-used tables))。

客户端验证:
客户端的验证是很有用的,但是只单独使用客户端验证一般是不可靠的。如果验证逻辑是用JavaScript来实现,通过关闭用户浏览器的 JavaScript可以很容易的绕过验证程序。但是,如果和其它技术(指Controlelr、Model或者数据库级别的验证技术)结合起来使用,客 户端验证会是一种给用户提供即时反馈的很方便的方式。

Controller级别的验证:
Controller级别的验证用起来看似很吸引人,但是经常会变得很难控制、难以测试和维护。只要有可能,保持你的Controllers尽量的“瘦”是个好主意(keep your controllers skinny )。从长远来看,这会给你的程序带来很多好处。

Model级别的验证:
Model级别的验证是确保只有通过验证的数据才能被保到数据库的最好方式。Model级别的验证是不依赖于数据库的,并且是不会被最终用户绕开 的,同时也是方便测试和维护的。Rails使得Model级别的验证很容易实现,为常见的需求提供了内置的helper,并且还允许你创建你自己的验证方 法。

验证什么时候发生?

Rails中有两种ActiveRecord对象:一种和数据库中的每一条记录相对应,另一种则不是。当你创建一个新的对象的时候,比如调用了某 个ActiveRecord类的new方法,创建出来的对象还不存在于数据库中。一旦你调用了这个对象的save方法,它将被保存到数据库对应的表中。 ActiveRecord使用new_record?实例方法来判断一个对象是否已经保存到数据库中。

创建和保存一个新的ActiveRecord对象会向数据库发送一条INSERT语句,更新一个ActiveRecord对象会向数据库发送一条 UPDATE语句。ActiveRecord的验证是在发送这些SQL语句之前进行的,如果验证不通过,对象将被标记为未通过验证的(invalid), 并且INSERT、UPDATE命令不会被执行,从而避免了把这些未通过验证的对象保存到数据库中。

有许多改变数据库中对象的状态的方法,其中一些方法会触发验证,而另一些则不会。这意味着如果不小心的话,把一个未通过验证的对象保存到数据库中是有可能的。

以下这些方法将会触发验证:
create
create!
save
save!
update
update_attributes
update_attributes!

其中带感叹号的方法(比如save!)在验证失败的时候将会抛出一个异常,不带感叹号的则不会:save和update_attributes返回false,create和update只会返回对象本身。

以下方法将会跳过验证,并把对象保存到数据库中,要小心使用:
decrement!
decrement_counter
increment!
increment_counter
toggle!
update_all
update_attribute
update_counters

同时要注意,假如给save方法传一个false参数也可以跳过验证,这个技巧也要小心使用。

valid?和invalid?
Rails使用valid?和invalid?方法来判断一个对象是否通过验证,这两个方法都会触发验证,如果验证通过,valid?返回true,invalid?返回false,否则相反。

可以通过ActiveRecord的实例方法errors来得到验证时发生的任何错误信息的集合(一个hash)。如果验证执行完毕,这个hash仍然是空的,说明这个对象通过验证。

errors.invalid?
errors.invalid?用于检查对象的某个属性是否合法,这个方法只能在对象的验证被触发之后调用,因为它只检查errors这个hash,而不会去触发验证。用法:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=errors.invalid%3F%20%3Aname%20%23true%7Cfalse" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. errors.invalid?  :name   #true|false   
errors.invalid? :name #true|false



Validation Helpers

validates_acceptance_of
validates_acceptance_of用于验证表单里的checkbox是否被勾上。需要用户同意一些服务条款是 validates_acceptance_of很典型的使用场景。这个“acceptance”不需要被持久化到数据库中(如果没有字段与之对 应,helper会创建一个虚拟属性(virtual attribute))。

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Person%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_acceptance_of%20%3Aterms_of_service%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Person < ActiveRecord::Base  
  2.  validates_acceptance_of :terms_of_service    
  3. end    
class Person < ActiveRecord::Base
 validates_acceptance_of :terms_of_service 
end 


validates_acceptance_of默认的错误消息是"must be accepted",每个Rails内建的验证helper都可以用:message 选项来指定错误消息:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=validates_acceptance_of%20%3Aterms_of_service%2C%20%3Amessage%3D%3E'some%20message'" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. validates_acceptance_of  :terms_of_service :message => 'some message'   
validates_acceptance_of :terms_of_service, :message=>'some message'


另外,validates_acceptance_of接受一个:accept选项,这个选项所指定的值用于判断“用户是否接受了服务条款”,如果没有指定,默认的值是字符串 "1"。

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=validates_acceptance_of%20%3Aterms_of_service%2C%20%3Aaccept%3D%3E'yes'%2C%20%3Amessage%3D%3E'some%20message'" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. validates_acceptance_of  :terms_of_service :accept => 'yes' :message => 'some message'   
validates_acceptance_of :terms_of_service, :accept=>'yes', :message=>'some message'



validates_associated
validates_associated用于验证关联的对象(调用valid?):

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Book%20%3C%20ActiveRecord%3A%3ABase%0A%20%20has_one%20%3Aauthor%0A%20%20validates_associated%20%3Aauthor%20%0Aend%0A%0Aclass%20Author%20%3C%20ActiveRecord%3A%3ABase%0A%20%20belongs_to%20%3Abook%0A%20%20validates_presence_of%20%3Aname%0Aend%0A%0Abook%20%3D%20Book.new%0Abook.author%20%3D%20Author.new%0Abook.valid%3F%20%23false%0Abook.errors.invalid%3F%20%3Aauthor%20%23true%0Abook.author.name%20%3D%20'somebody'%0Abook.valid%3F%20%23true%0A" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Book < ActiveRecord::Base  
  2.   has_one :author   
  3.   validates_associated :author    
  4. end   
  5.   
  6. class  Author < ActiveRecord::Base  
  7.   belongs_to :book   
  8.   validates_presence_of :name   
  9. end   
  10.   
  11. book = Book.new   
  12. book.author = Author.new   
  13. book.valid? #false   
  14. book.errors.invalid? :author   #true   
  15. book.author.name = 'somebody'   
  16. book.valid? #true   
class Book < ActiveRecord::Base
  has_one :author
  validates_associated :author 
end

class Author < ActiveRecord::Base
  belongs_to :book
  validates_presence_of :name
end

book = Book.new
book.author = Author.new
book.valid? #false
book.errors.invalid? :author #true
book.author.name = 'somebody'
book.valid? #true


要注意的一点是,别在相关联的两个类中同时使用validates_associated,否则在触发验证的时候会引起无限循环。

validates_confirmation_of
validates_confirmation_of用于检查两个字段的内容是否相同,比如在“用户注册”的时候,可以用它检查“密码”和“确认密码”、“邮箱”和“确认邮箱”的内容是否相同。
这个helper会创建一个虚拟属性,这个虚拟属性的名字以被要求确认的属性名开头,以_confirmation结尾:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Person%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_confirmation_of%20%3Aemail%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Person < ActiveRecord::Base  
  2.  validates_confirmation_of :email    
  3. end    
class Person < ActiveRecord::Base
 validates_confirmation_of :email 
end 


在view模板里可以这样用:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=%3C%25%3D%20text_field%20%3Aperson%2C%20%3Aemail%20%25%3E%20%0A%3C%25%3D%20text_field%20%3Aperson%2C%20%3Aemail_confirmation%20%25%3E%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. <%= text_field  :person :email  %>   
  2. <%= text_field :person :email_confirmation  %>   
<%= text_field :person, :email %> 
<%= text_field :person, :email_confirmation %> 


检查只在email_confirmation不为nil的时候执行,所以需要给email_confirmation添加一个validates_presence_of 验证,像这样:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Person%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_confirmation_of%20%3Aemail%0A%20validates_presence_of%20%3Aemail_confirmation%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Person < ActiveRecord::Base  
  2.  validates_confirmation_of :email   
  3.  validates_presence_of :email_confirmation    
  4. end    
class Person < ActiveRecord::Base
 validates_confirmation_of :email
 validates_presence_of :email_confirmation 
end 


validates_exclusion_of
validates_exclusion_of用于保证对象的属性值不在指定的集合中,例如在注册域名的时候,"www"是预留的,不允许用户注册,可以这样:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Account%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_exclusion_of%20%3Asubdomain%2C%20%3Ain%20%3D%3E%20%25w(www)%2C%0A%20%3Amessage%20%3D%3E%20%22Subdomain%20%7B%7Bvalue%7D%7D%20is%20reserved.%22%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Account < ActiveRecord::Base  
  2.  validates_exclusion_of :subdomain :in  => %w(www),  
  3.  :message  =>  "Subdomain {{value}} is reserved."    
  4. end    
class Account < ActiveRecord::Base
 validates_exclusion_of :subdomain, :in => %w(www),
 :message => "Subdomain {{value}} is reserved." 
end 


:in选项接受一个集合,这个集合可以是任何可枚举的对象(enumerable object),集合里存放的是那些被排除的值。另外,:in有个别名:within。这里:message的用法展示了如何在消息中包含属性值({{value}})。

validates_format_of
validates_format_of用于验证文本的格式,有个:with选项,用来指定要匹配的正则表达式:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Product%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_format_of%20%3Alegacy_code%2C%20%3Awith%20%3D%3E%20%2F%5CA%5Ba-zA-Z%5D%2B%5Cz%2F%2C%0A%20%3Amessage%20%3D%3E%20%22Only%20letters%20allowed%22%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Product < ActiveRecord::Base  
  2.  validates_format_of :legacy_code :with  => /\A[a-zA-Z]+\z/,  
  3.  :message  =>  "Only letters allowed"    
  4. end    
class Product < ActiveRecord::Base
 validates_format_of :legacy_code, :with => /\A[a-zA-Z]+\z/,
 :message => "Only letters allowed" 
end 



validates_inclusion_of
validates_inclusion_of用于确保对象的属性值在指定的集合中,例如:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Coffee%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_inclusion_of%20%3Asize%2C%20%3Ain%20%3D%3E%20%25w(small%20medium%20large)%2C%0A%20%3Amessage%20%3D%3E%20%22%7B%7Bvalue%7D%7D%20is%20not%20a%20valid%20size%22%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Coffee < ActiveRecord::Base  
  2.  validates_inclusion_of :size :in  => %w(small medium large),  
  3.  :message  =>  "{{value}} is not a valid size"    
  4. end    
class Coffee < ActiveRecord::Base
 validates_inclusion_of :size, :in => %w(small medium large),
 :message => "{{value}} is not a valid size" 
end 


这样,Coffee的size(……Coffee的size是个什么概念?)只能为"small"、"medium"或者"large"。同样,这里的:in也有一个别名:within。

validates_length_of(别名validates_size_of)
validates_length_of看着简单,用法却很多。用于指定某属性的字符串长度,有多种指定方式,比如最大值、最小值、在某个区间内或者直接指定长度:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Person%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_length_of%20%3Aname%2C%20%3Aminimum%20%3D%3E%202%0A%20validates_length_of%20%3Abio%2C%20%3Amaximum%20%3D%3E%20500%0A%20validates_length_of%20%3Apassword%2C%20%3Ain%20%3D%3E%206..20%0A%20validates_length_of%20%3Aregistration_number%2C%20%3Ais%20%3D%3E%206%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Person < ActiveRecord::Base  
  2.  validates_length_of :name :minimum  => 2  
  3.  validates_length_of :bio :maximum  => 500  
  4.  validates_length_of :password :in  => 6..20  
  5.  validates_length_of :registration_number :is  => 6   
  6. end    
class Person < ActiveRecord::Base
 validates_length_of :name, :minimum => 2
 validates_length_of :bio, :maximum => 500
 validates_length_of :password, :in => 6..20
 validates_length_of :registration_number, :is => 6 
end 


:message选项可以用:wrong_length、:too_long、和:too_short来替代。根据情况选择,比如:minimun对应:too_short。在message里可以使用{{count}}作为允许长度的占位符:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Person%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_length_of%20%3Abio%2C%20%3Amaximum%20%3D%3E%201000%2C%0A%20%3Atoo_long%20%3D%3E%20%22%7B%7Bcount%7D%7D%20characters%20is%20the%20maximum%20allowed%22%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Person < ActiveRecord::Base  
  2.  validates_length_of :bio :maximum  => 1000,  
  3.  :too_long  =>  "{{count}} characters is the maximum allowed"    
  4. end    
class Person < ActiveRecord::Base
 validates_length_of :bio, :maximum => 1000,
 :too_long => "{{count}} characters is the maximum allowed" 
end 


另外,可以使用指定的算法来分割字符串,计算字符串的长度(估计是考虑到双字节字符,例如中文)。:tokenizer用于指定分割算法:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Essay%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_length_of%20%3Acontent%2C%20%3Aminimum%20%3D%3E%20300%2C%0A%20%3Amaximum%20%3D%3E%20400%2C%0A%20%3Atokenizer%20%3D%3E%20lambda%20%7B%20%7Cstr%7C%20str.scan(%2F%5Cw%2B%2F)%20%7D%2C%0A%20%3Atoo_short%20%3D%3E%20%22must%20have%20at%20least%20%7B%7Bcount%7D%7D%20words%22%2C%0A%20%3Atoo_long%20%3D%3E%20%22must%20have%20at%20most%20%7B%7Bcount%7D%7D%20words%22%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Essay < ActiveRecord::Base  
  2.  validates_length_of :content :minimum  => 300,  
  3.  :maximum  => 400,  
  4.  :tokenizer  => lambda { |str| str.scan(/\w+/) },  
  5.  :too_short  =>  "must have at least {{count}} words" ,  
  6.  :too_long  =>  "must have at most {{count}} words"    
  7. end    
class Essay < ActiveRecord::Base
 validates_length_of :content, :minimum => 300,
 :maximum => 400,
 :tokenizer => lambda { |str| str.scan(/\w+/) },
 :too_short => "must have at least {{count}} words",
 :too_long => "must have at most {{count}} words" 
end 


validates_numericality_of
validates_numericality_of用于验证某属性值是否为数字。它默认允许整数和浮点数,如果你只希望得到一个整数,那么可以设置:only_integer选项的值为true,这样Rails将会使用正则表达式

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=%2F%5CA%5B%2B-%5D%3F%5Cd%2B%5CZ%2F" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. /\A[+-]?\d+\Z/  
/\A[+-]?\d+\Z/

来匹配属性值。

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Player%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_numericality_of%20%3Apoints%0A%20validates_numericality_of%20%3Agames_played%2C%20%3Aonly_integer%20%3D%3E%20true%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Player < ActiveRecord::Base  
  2.  validates_numericality_of :points   
  3.  validates_numericality_of :games_played :only_integer  =>  true   
  4. end    
class Player < ActiveRecord::Base
 validates_numericality_of :points
 validates_numericality_of :games_played, :only_integer => true
end 


除了:only_integer,validates_numericality_of 还有许多其它选项:

引用
:greater_than – Specifies the value must be greater than the supplied value. The default error message for this option is “must be greater than {{count}}”.
:greater_than_or_equal_to – Specifies the value must be greater than or equal to the supplied value. The default error message for this option is “_must be greater than or equal to {{count}}”.
:equal_to – Specifies the value must be equal to the supplied value. The default error message for this option is “must be equal to {{count}}”.
:less_than – Specifies the value must be less than the supplied value. The default error message for this option is “must be less than {{count}}”.
:less_than_or_equal_to – Specifies the value must be less than or equal the supplied value. The default error message for this option is “must be less or equal to {{count}}”.
:odd – Specifies the value must be an odd number if set to true. The default error message for this option is “must be odd”.
:even – Specifies the value must be an even number if set to true. The default error message for this option is “must be even”.


validates_presence_of
validates_presence_of在前面见过,用于验证“必填”的属性,它会调用对象属性的blank?方法来判断:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Person%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_presence_of%20%3Aname%2C%20%3Alogin%2C%20%3Aemail%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Person < ActiveRecord::Base  
  2.  validates_presence_of :name :login :email    
  3. end    
class Person < ActiveRecord::Base
 validates_presence_of :name, :login, :email 
end 


由于false.blank?的值是true,如果你想验证某个布尔属性是否被赋值,应当这样做:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=validates_inclusion_of%20%3Afield_name%2C%20%3Ain%20%3D%3E%20%5Btrue%2C%20false%5D" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. validates_inclusion_of  :field_name :in  => [ true false ]  
validates_inclusion_of :field_name, :in => [true, false]


validates_uniqueness_of
validates_uniqueness_of用来确保某属性的唯一性,比如“用户注册”时的用户名、email等。一般用法:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Account%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_uniqueness_of%20%3Aemail%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Account < ActiveRecord::Base  
  2.  validates_uniqueness_of :email   
  3. end    
class Account < ActiveRecord::Base
 validates_uniqueness_of :email
end 


这个验证在触发时会执行一条SQL语句(大概像这样SELECT * FROM accounts WHERE email='foo@bar.com')。
这个helper有一个:scope选项,用于限制查询的范围,比如:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Holiday%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_uniqueness_of%20%3Aname%2C%20%3Ascope%20%3D%3E%20%3Ayear%2C%0A%20%3Amessage%20%3D%3E%20%22should%20happen%20once%20per%20year%22%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Holiday < ActiveRecord::Base  
  2.  validates_uniqueness_of :name :scope  =>  :year ,  
  3.  :message  =>  "should happen once per year"    
  4. end    
class Holiday < ActiveRecord::Base
 validates_uniqueness_of :name, :scope => :year,
 :message => "should happen once per year" 
end 


还有个:case_sensitive用于指定是否忽略大小写:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Person%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_uniqueness_of%20%3Aname%2C%20%3Acase_sensitive%20%3D%3E%20false%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Person < ActiveRecord::Base  
  2.  validates_uniqueness_of :name :case_sensitive  =>  false    
  3. end    
class Person < ActiveRecord::Base
 validates_uniqueness_of :name, :case_sensitive => false 
end 


validates_each
这个helper需要靠一个block来验证属性,它没有预定义的函数,但可以使用block创建一个验证规则,所有传递给validates_each的属性都靠这个规则来验证。在下面这个例子中,我们希望name和surname不以小写字母开头:

Java代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Person%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_each%20%3Aname%2C%20%3Asurname%20do%20%7Cmodel%2C%20attr%2C%20value%7C%0A%20%20model.errors.add(attr%2C%20'must%20start%20with%20upper%20case')%20if%20value%20%3D~%20%2F%5CA%5Ba-z%5D%2F%0A%20end%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Person < ActiveRecord::Base  
  2.  validates_each :name, :surname do  |model, attr, value|  
  3.   model.errors.add(attr, 'must start with upper case' if  value =~ /\A[a-z]/  
  4.  end   
  5. end   
class Person < ActiveRecord::Base
 validates_each :name, :surname do |model, attr, value|
  model.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/
 end 
end 


这里的block接收3个参数,分别是model对象本身、属性名和属性值。

validation helper中常见的选项

:allow_nil 顾名思义。值为true或false。另外,guides上面说:

引用
Using :allow_nil with validates_presence_of allows for nil, but any other blank? value will still be rejected.


但经试验,发现好像并不是这样,:allow_nil=>true在validates_presence_of里好像不起作用。
:allow_blank

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Topic%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_length_of%20%3Atitle%2C%20%3Ais%20%3D%3E%205%2C%20%3Aallow_blank%20%3D%3E%20true%20%0Aend%20%0ATopic.create(%22title%22%20%3D%3E%20%22%22).valid%3F%20%23%20%3D%3E%20true%20%0ATopic.create(%22title%22%20%3D%3E%20nil).valid%3F%20%23%20%3D%3E%20true%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Topic < ActiveRecord::Base  
  2.  validates_length_of :title :is  => 5,  :allow_blank  =>  true    
  3. end    
  4. Topic.create("title"  =>  "" ).valid?  # => true    
  5. Topic.create("title"  =>  nil ).valid?  # => true    
class Topic < ActiveRecord::Base
 validates_length_of :title, :is => 5, :allow_blank => true 
end 
Topic.create("title" => "").valid? # => true 
Topic.create("title" => nil).valid? # => true 


:message 这里就不用解释了。
:on
:on选项允许设置验证触发的时机。Rails默认触发验证的时机是在保存对象之前(save、create、update)。如果你想改变这一规则,可以使用:on选项,比如:on=>:save会使验证只在save方法被调用之前 触发验证。

Conditional Validation

:if和:unless选项
这两个选项用于设置验证触发的条件,值可以是symbol,可以是string,也可以是一个lambda/proc。
当值为symbol时,Rails会在验证触发之前调用symbol对应的方法,再根据返回结果决定是否执行验证;
当值为string时,Rails会在验证触发之前用eval来执行这个string,再根据返回结果决定是否执行验证;
当值为lambda/proc表达式时,Rails会在验证触发之前执行这个表达式,再根据返回结果决定是否执行验证。

自定义验证
当Rails内建的验证规则满足不了你的需求时,可以用validate、validate_on_create或者validate_on_update 自定义验证规则。它的参数是一个或多个symbol,这些symbol每个都对应一个方法(同名),这些方法将在验证触发的时候被调用。
另外,甚至可以这样定义自己的validation helper:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=ActiveRecord%3A%3ABase.class_eval%20do%20%0A%20def%20self.validates_as_radio(attr_name%2C%20n%2C%20options%3D%7B%7D)%0A%20%20validates_inclusion_of%20attr_name%2C%20%7B%3Ain%20%3D%3E%201..n%7D.merge(options)%20%0A%20end%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. ActiveRecord::Base.class_eval  do    
  2.  def   self .validates_as_radio(attr_name, n, options={})  
  3.   validates_inclusion_of attr_name, {:in  => 1..n}.merge(options)   
  4.  end    
  5. end    
ActiveRecord::Base.class_eval do 
 def self.validates_as_radio(attr_name, n, options={})
  validates_inclusion_of attr_name, {:in => 1..n}.merge(options) 
 end 
end 

 

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Movie%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_as_radio%20%3Arating%2C%205%20%0Aend" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Movie < ActiveRecord::Base  
  2.  validates_as_radio :rating , 5   
  3. end   
class Movie < ActiveRecord::Base
 validates_as_radio :rating, 5 
end



Working with Validation Errors

errors.add_to_base
errors.add_to_base用于将error添加到对象上而不是对象的某个具体属性上。使用很简单,只要给它一个string参数作为错误信息。

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Person%20%3C%20ActiveRecord%3A%3ABase%0A%20def%20a_method_used_for_validation_purposes%0A%20%20errors.add_to_base(%22This%20person%20is%20invalid%20because%20...%22)%20%0A%20end%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Person < ActiveRecord::Base  
  2.  def  a_method_used_for_validation_purposes  
  3.   errors.add_to_base("This person is invalid because ..." )   
  4.  end    
  5. end    
class Person < ActiveRecord::Base
 def a_method_used_for_validation_purposes
  errors.add_to_base("This person is invalid because ...") 
 end 
end 


errors.add
errors.add用于将error添加到对象某个特定的属性上。可以使用full_messages 方法来查看将会显示在页面上的错误信息:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Person%20%3C%20ActiveRecord%3A%3ABase%0A%20def%20a_method_used_for_validation_purposes%0A%20%20errors.add(%3Aname%2C%20%22cannot%20contain%20the%20characters%20!%40%23%25*()_-%2B%3D%22)%20%0A%20end%20%0Aend%20%0A%0Aperson%20%3D%20Person.create(%3Aname%20%3D%3E%20%22!%40%23%22)%20%0Aperson.errors.on(%3Aname)%20%20%23%20%3D%3E%20%22cannot%20contain%20the%20characters%20!%40%23%25*()_-%2B%3D%22%20%0Aperson.errors.full_messages%20%23%20%3D%3E%20%5B%22Name%20cannot%20contain%20the%20characters%20!%40%23%25*()_-%2B%3D%22%5D%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Person < ActiveRecord::Base  
  2.  def  a_method_used_for_validation_purposes  
  3.   errors.add(:name "cannot contain the characters !@#%*()_-+=" )   
  4.  end    
  5. end    
  6.   
  7. person = Person.create(:name  =>  "!@#" )   
  8. person.errors.on(:name )   # => "cannot contain the characters !@#%*()_-+="    
  9. person.errors.full_messages # => ["Name cannot contain the characters !@#%*()_-+="]    
class Person < ActiveRecord::Base
 def a_method_used_for_validation_purposes
  errors.add(:name, "cannot contain the characters !@#%*()_-+=") 
 end 
end 

person = Person.create(:name => "!@#") 
person.errors.on(:name)  # => "cannot contain the characters !@#%*()_-+=" 
person.errors.full_messages # => ["Name cannot contain the characters !@#%*()_-+="] 


errors.on
errors.on用于检查某个特定属性的错误信息。它根据指定的属性的不同状态返回不同的对象:如果指定的属性没有错误,errors.on返 回nil;如果指定的属性有1个错误,errors.on返回这个错误的message(字符串);如果指定的属性有多个错误,errors.on返回这 些错误的message(字符串)数组。

errors.clear
errors.clear用于清除错误信息。

引用
Of course, calling errors.clear upon an invalid object won’t actually make it valid: the errors collection will now be empty, but the next time you call valid? or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the errors collection will be filled again.


errors.size 不用解释。

Displaying Validation Errors in the View
当使用form_for来创建表单的时候,可以使用form builder的error_messaages方法来显示验证错误的结果。

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Product%20%3C%20ActiveRecord%3A%3ABase%0A%20validates_presence_of%20%3Adescription%2C%20%3Avalue%20%0A%20validates_numericality_of%20%3Avalue%2C%20%3Aallow_nil%20%3D%3E%20true%20%0Aend%20%0A%0A%3C%25%20form_for(%40product)%20do%20%7Cf%7C%20%25%3E%20%0A%20%3C%25%3D%20f.error_messages%20%25%3E%0A%20%20%3Cp%3E%0A%20%20%20%3C%25%3D%20f.label%20%3Adescription%20%25%3E%3Cbr%20%2F%3E%0A%20%20%20%3C%25%3D%20f.text_field%20%3Adescription%20%25%3E%0A%20%20%3C%2Fp%3E%0A%20%20%3Cp%3E%0A%20%20%20%3C%25%3D%20f.label%20%3Avalue%20%25%3E%3Cbr%20%2F%3E%0A%20%20%20%3C%25%3D%20f.text_field%20%3Avalue%20%25%3E%0A%20%20%3C%2Fp%3E%0A%20%20%3Cp%3E%0A%20%20%20%3C%25%3D%20f.submit%20%22Create%22%20%25%3E%0A%20%20%3C%2Fp%3E%20%0A%3C%25%20end%20%25%3E%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Product < ActiveRecord::Base  
  2.  validates_presence_of :description :value    
  3.  validates_numericality_of :value :allow_nil  =>  true    
  4. end    
  5.   
  6. <% form_for(@product do  |f| %>   
  7.  <%= f.error_messages %>  
  8.   <p>  
  9.    <%= f.label :description  %><br />  
  10.    <%= f.text_field :description  %>  
  11.   </p>  
  12.   <p>  
  13.    <%= f.label :value  %><br />  
  14.    <%= f.text_field :value  %>  
  15.   </p>  
  16.   <p>  
  17.    <%= f.submit "Create"  %>  
  18.   </p>   
  19. <% end  %>   
class Product < ActiveRecord::Base
 validates_presence_of :description, :value 
 validates_numericality_of :value, :allow_nil => true 
end 

<% form_for(@product) do |f| %> 
 <%= f.error_messages %>
  <p>
   <%= f.label :description %><br />
   <%= f.text_field :description %>
  </p>
  <p>
   <%= f.label :value %><br />
   <%= f.text_field :value %>
  </p>
  <p>
   <%= f.submit "Create" %>
  </p> 
<% end %> 


也可以使用error_messages_for这个helper来达到同样的效果:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=%3C%25%3D%20error_messages_for%20%3Aproduct%20%25%3E%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. <%= error_messages_for  :product  %>   
<%= error_messages_for :product %> 


这两个方法都接受3个同样的选项::header_message, :message和:header_tag。下面是效果对比:

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=%3C%25%3D%20error_messages_for%20%3Abook%20%25%3E" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. <%= error_messages_for  :book  %>  
<%= error_messages_for :book %>


Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=%3C%25%3D%20error_messages_for%20%3Abook%2C%20%3Aheader_message%3D%3E'header_message'%2C%0A%09%09%3Amessage%3D%3E'message'%2C%20%3Aheader_tag%3D%3E'h1'%25%3E" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. <%= error_messages_for  :book :header_message => 'header_message' ,  
  2.         :message => 'message' :header_tag => 'h1' %>  
<%= error_messages_for :book, :header_message=>'header_message',
		:message=>'message', :header_tag=>'h1'%>


Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=%3C%25%3D%20error_messages_for%20%3Abook%2C%20%3Aheader_message%3D%3Enil%2C%0A%09%09%3Amessage%3D%3Enil%2C%20%3Aheader_tag%3D%3Enil%25%3E" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. <%= error_messages_for  :book :header_message => nil ,  
  2.         :message => nil :header_tag => nil %>  
<%= error_messages_for :book, :header_message=>nil,
		:message=>nil, :header_tag=>nil%>



8.2 Customizing the Error Messages CSS
8.3 Customizing the Error Messages HTML 略:

http://guides.rubyonrails.org/activerecord_validations_callbacks.html#customizing-the-error-messages-css

Callback Registration

callbacks的参数可以是对应某个方法的symbol,也可以是一个block。

引用
Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations :
10.1 Creating an Object

    * before_validation
    * before_validation_on_create
    * after_validation
    * after_validation_on_create
    * before_save
    * before_create
    * INSERT OPERATION
    * after_create
    * after_save

10.2 Updating an Object

    * before_validation
    * before_validation_on_update
    * after_validation
    * after_validation_on_update
    * before_save
    * before_update
    * UPDATE OPERATION
    * after_update
    * after_save

10.3 Destroying an Object

    * before_destroy
    * DELETE OPERATION
    * after_destroy

after_save runs both on create and update, but always after the more specific callbacks after_create and after_update, no matter the order in which the macro calls were executed.


另外,after_initialize 将在Active Record对象实例化之后被调用。包括调用类方法new或者从数据库中加载对象。
after_find 将在Active Record从数据库加载对象之后调用,如果同时定义了after_initialize,after_find将先被调用。
注意,after_initialize和after_find这两个callbacks和其它的有点不同。首先,这两个callbacks没有 对应的before_* callbacks。同时,由于性能上的原因,使用它们的唯一方式是将它们定义为一个普通的方法,否则这两个callbacks将被忽略。(This behaviour is due to performance reasons, since after_initialize and after_find will both be called for each record found in the database, significantly slowing down the queries. 说实话,其实看不太明白。。):

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20User%20%3C%20ActiveRecord%3A%3ABase%0A%20def%20after_initialize%0A%20%20puts%20%22You%20have%20initialized%20an%20object!%22%20%0A%20end%20%0A%20def%20after_find%0A%20%20puts%20%22You%20have%20found%20an%20object!%22%20%0A%20end%20%0Aend%20" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  User < ActiveRecord::Base  
  2.  def  after_initialize  
  3.   puts "You have initialized an object!"    
  4.  end    
  5.  def  after_find  
  6.   puts "You have found an object!"    
  7.  end    
  8. end    
class User < ActiveRecord::Base
 def after_initialize
  puts "You have initialized an object!" 
 end 
 def after_find
  puts "You have found an object!" 
 end 
end 


Running Callbacks

下面的方法将会触发callbacks:
    *  create
    * create!
    * decrement!
    * destroy
    * destroy_all
    * increment!
    * save
    * save!
    * save(false)
    * toggle!
    * update
    * update_attribute
    * update_attributes
    * update_attributes!
    * valid?
after_find callbacks会被以下方法触发:
    * all
    * first
    * find
    * find_all_by_attribute
    * find_by_attribute
    * find_by_attribute!
    * last
以下方法会跳过callbacks:
    *  decrement
    * decrement_counter
    * delete
    * delete_all
    * find_by_sql
    * increment
    * increment_counter
    * toggle
    * update_all
    * update_counters

Conditional Callbacks
同Conditional Validation ,只是Conditional Callbacks支持:if和:unless混用。

Ruby代码 <embed type="application/x-shockwave-flash" width="14" height="15" src="http://yuan.iteye.com/javascripts/syntaxhighlighter/clipboard_new.swf" flashvars="clipboard=class%20Comment%20%3C%20ActiveRecord%3A%3ABase%0A%20after_create%20%3Asend_email_to_author%2C%20%3Aif%20%3D%3E%20%3Aauthor_wants_emails%3F%2C%20%0A%20%3Aunless%20%3D%3E%20Proc.new%20%7B%20%7Ccomment%7C%20comment.post.ignore_comments%3F%20%7D%20%0Aend%20%0A" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
  1. class  Comment < ActiveRecord::Base  
  2.  after_create :send_email_to_author <span class
    分享到:
    评论

相关推荐

Global site tag (gtag.js) - Google Analytics