Ruby-on-rails 了解 Rails 验证:allow_blank 有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14488465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:19:25  来源:igfitidea点击:

Understanding Rails validation: what does allow_blank do?

ruby-on-rails

提问by Slevin

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.

我对 Rails 很陌生,发现了一个小片段来逐步验证存在性和唯一性:首先检查存在性,然后检查唯一性。

validates :email, :presence => true, :allow_blank => true, :uniqueness => { :case_sensitive => false }

I'm a little bit confused about using presence => trueand allow_blank => truetogether.

我对使用presence => trueallow_blank => true一起使用有点困惑。

Without using allow_blank => trueboth rules will be checked at the same time and not step by step.

不使用allow_blank => true这两个规则会同时检查,而不是一步一步检查。

Why does allow_blank => truedo this magic?

为什么会产生allow_blank => true这种魔法?

采纳答案by Philip Hallstrom

What you've got is equivalent to this (wrapped for clarity):

你所拥有的相当于这个(为了清楚起见包装):

validates :email, :presence => true, 
            :uniqueness => { :allow_blank => true, :case_sensitive => false }

That's a little silly though since if you're requiring presence, then that's going to "invalidate" the :allow_blank clause to :uniqueness.

虽然这有点愚蠢,因为如果您需要存在,那么这将使 :allow_blank 子句“无效”为 :uniqueness。

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.

当您切换到使用其他验证器时更有意义...说...格式和唯一性,但如果它是空白的,您不需要任何检查。在这种情况下,添加一个“全局应用” :allow_blank 更有意义,并且 DRY 稍微增加了代码。

This...

这个...

validates :email, :format => {:allow_blank => true, ...}, 
                  :uniqueness => {:allow_blank => true, ...}

can be written like:

可以写成:

validates :email, :allow_blank => true, :format => {...}, :uniqueness => {...}

回答by Dennis

The following distinction can be useful to know:

了解以下区别可能很有用:

presence: true                    # nil and empty string fail validation
presence: true, allow_blank: true # nil fails validation, empty string passes

回答by graywh

:allow_blankis an option that will "disable" several of the validators, but not the presence validator. The result of using these two together is that when the field is left blank, you will get the :blankerror message (i.e., "can't be blank"), but not the other error messages.

:allow_blank是一个选项,将“禁用”多个验证器,但不会“禁用”存在验证器。将这两者结合使用的结果是,当该字段留空时,您将收到:blank错误消息(即“不能为空”),但不会收到其他错误消息。

回答by Jordan Brough

In your code, :presence =>and :uniqueness =>are validators, while :allow_blank =>is a default option that gets passed to other validators.

在您的代码中,:presence =>并且:uniqueness =>是验证器,:allow_blank =>而是传递给其他验证器的默认选项。

So your code:

所以你的代码:

validates(
    :email,
    :presence => true,
    :allow_blank => true,
    :uniqueness => { :case_sensitive => false }
)

Is equivalent to this code:

相当于这个代码:

validates(
    :email,
    :presence => { :allow_blank => true },
    :uniqueness => { :allow_blank => true, :case_sensitive => false }
)

However, the presencevalidator ignores the allow_blankoption, so your code ends up being essentially this:

但是,presence验证器会忽略该allow_blank选项,因此您的代码最终基本上是这样的:

validates(
    :email,
    :presence => { }, # `{ }` is equivalent to `true`
    :uniqueness => { :allow_blank => true, :case_sensitive => false }
)

Having :allow_blank => truein :uniquenessmeans that when the email is blank, the uniquenessvalidation will not be run.

:allow_blank => true:uniqueness指当电子邮件为空,则uniqueness验证不会运行。

One effect of this is that you eliminate a DB query.

这样做的一个效果是您消除了数据库查询。

E.g., withoutthe :allow_blank => truecondition you would see this:

例如,没有:allow_blank => true条件,你会看到这一点:

>> user = User.new(email: nil)
>> user.valid?
  User Exists (0.2ms) SELECT  1 AS one FROM "users" WHERE "users"."name" IS NULL LIMIT 1
=> false
>> user.errors.messages
=> {:email=>["can't be blank"]}

But withthe :allow_blank => trueoption you won't see that User ExistsDB query happen.

但是使用:allow_blank => true选项,您将看不到User ExistsDB 查询发生。

Another edge-case side effect happens when you havea record with a blank email address in your DB already. In that case if you don'thave the :allow_blank => trueoption on the uniquenessvalidator, then you'll see two errors come back:

当您另一种边缘情况下的副作用发生与您的数据库空白的电子邮件地址已经是一个纪录。在这种情况下,如果您没有验证器:allow_blank => true上的选项uniqueness,那么您将看到两个错误返回:

>> user = User.new(email: nil)
>> user.valid?
  User Exists (0.2ms) SELECT  1 AS one FROM "users" WHERE "users"."name" IS NULL LIMIT 1
=> false
>> user.errors.messages
=> {:email=>["has already been taken", "can't be blank"]}

But withthe :allow_blank => trueoption you'll only see the "can't be blank"error (because the uniqueness validation won't run when the email is blank).

但是使用:allow_blank => true选项,您只会看到"can't be blank"错误(因为当电子邮件为空白时不会运行唯一性验证)。

回答by cbd Focus

from Rails annotation

来自 Rails 注释

# * <tt>:allow_nil</tt> - Skip validation if the attribute is +nil+.
# * <tt>:allow_blank</tt> - Skip validation if the attribute is blank.

so, it means when we use allow_blankon email, if the email is nil, only one error added to errorsobject, jump the uniqueness validates.

所以,这意味着当我们allow_blank在电子邮件上使用时,如果电子邮件为零,则只向errors对象添加一个错误,跳转唯一性验证。

回答by gy134340

Too much explain just make simple things more complicated, let's just say:

太多的解释只会把简单的事情变得更复杂,我们就说:

# do not use this validates to check if the value is blank