假设我为了让用户输入的数据长度不超过数据库定义的长度,定义了如下validation:
ruby 代码
- class User < ActiveRecord::Base
- validates_length_of :name, :maximum => 50
- end
上面代码的行为有时却颇为怪异:
ruby 代码
- ruby script/console
-
- >> u = User.new
- =>
- >> u.valid?
- => false
- >> u.errors.full_messages
- =>["Name is too long (maximum is 50 characters)"]
注意当user对象的name为nil时,输出的错误却是["name is too long (maximum is 50 characters)"],驴唇不对马嘴!但事实确实如此,为什么?原因在于rails的所有validation方法都支持一个可选参数:allow_nil。allow_nil默认为false, 所以当user对象的name属性为nil时, 尽管is nil与is too long是两回事,validates_length_of :name, :maximum => 50 这个验证却不会通过。
当然你可以指定:allow_nil => true, 但问题是有些属性不能为nil, 即是必须的属性,这时就会想到validates_presence_of,我们可以对上面的代码做改进:
ruby 代码
- class User < ActiveRecord::Base
- validates_length_of :name, :maximum => 50, :allow_nil => true
- validates_presence_of :name
- end
分享到:
相关推荐
Standard Gotchas-in the Verilog and SystemVerilog Standards That Every Engineer Should Know 。 The Verilog and SystemVerilog standards define hundreds of subtle rules on how software tools should ...
C++ Gotchas Avoiding Common Problems in Coding and Design 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除
Provides intermediate programmers with the practical know-how needed to gain expert status.-- In the prestigious Addison-Wesley Professional Computing Series C++ Gotchas is the latest addition to the ...
verilog and systemverilog 101 gotchas.pdf, a good ebook for hardware desinger ant testers.
Thinking in C++ Accelerated C++ C++ Gotchas C++初学者50个忠告中提及的资料整理[分10卷下载 每卷50M]\C++初学者50个忠告中提及的资料整理[分10卷下载每卷50M].part01
C++程序设计陷阱(C++Gotchas)
c++程序设计陷阱,中英文都有的哦,很有用的
C++程序设计陷阱(C++Gotchas) 包含中英两个版本
好的C++ 图书,帮你更加了解C++,希望你学习C++更加愉快
STL Gotchas.pdf
Addison.Wesley.Stephen.C.Dewhurst.C++.Gotchas-.Avoiding.Common.Problems.in.Coding.and.Design
Addison Wesley - C++ Gotchas .chm 好书不用多说~~~
[AddisonWesley]C++_Gotchas.zip
microsoft.net gotchasmicrosoft.net gotchasmicrosoft.net gotchas
vc编程系列之Addison Wesley - C++ Gotchas
一些陷阱R函数有一些潜在的令人惊讶的结果,需要注意。 是一个包含更多内容的stackoverflow讨论。 甚至更多:以及更多:尺寸下降对于矩阵: m <- matrix ( 1 : 6 , ncol = 3 )m ## [,1] [,2] [,3]## [1,] 1 3 5##...
Verilog and system verilog学习的好资料, Verilog and SystemVerilog Gotchas_101 Common Coding Errors and How to Avoid Them