了解 Rails 验证:allow_blank 有什么作用? [英] Understanding Rails validation: what does allow_blank do?
问题描述
我对 Rails 很陌生,发现了一个小片段来逐步验证存在性和唯一性:首先检查存在性,然后检查唯一性.
I'm quite new to Rails and found a little snippet to validate presence and uniqueness step by step: first check presence, then check uniqueness.
validates :email, :presence => true, :allow_blank => true, :uniqueness => { :case_sensitive => false }
我对使用 presence => 有点困惑true
和 allow_blank =>真的
在一起.
I'm a little bit confused about using presence => true
and allow_blank => true
together.
不使用 allow_blank =>true
两条规则会同时检查,而不是一步一步检查.
Without using allow_blank => true
both rules will be checked at the same time and not step by step.
为什么 allow_blank =>真的
会变魔术吗?
推荐答案
您所拥有的与此等效(为了清晰起见,已封装):
What you've got is equivalent to this (wrapped for clarity):
validates :email, :presence => true,
:uniqueness => { :allow_blank => true, :case_sensitive => false }
虽然这有点愚蠢,因为如果您需要存在,那么这将无效":allow_blank
子句到 :uniqueness
.
That's a little silly though since if you're requiring presence, then that's going to "invalidate" the :allow_blank
clause to :uniqueness
.
当您切换到使用其他验证器时更有意义.. 比如说... format
和 uniqueness
,但是如果它是空白的,您就不需要任何检查.在这种情况下,添加全局应用":allow_blank
更有意义,DRY 对代码进行了一些改进.
It makes more sense when you switch to using other validators.. say... format
and uniqueness
, but you don't want any checks if it's blank. In this case, adding a "globally applied" :allow_blank
makes more sense and DRY's up the code a little bit.
这...
validates :email, :format => {:allow_blank => true, ...},
:uniqueness => {:allow_blank => true, ...}
可以写成:
validates :email, :allow_blank => true, :format => {...}, :uniqueness => {...}
这篇关于了解 Rails 验证:allow_blank 有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!