简体   繁体   English

验证与validate_uniquess_of?

[英]validate vs validate_uniquess_of?

Is there a difference between using使用有区别吗

validates :foo, uniqueness: true

or或者

validates_uniqueness_of :foo ? validates_uniqueness_of :foo ?

I know this is a simple questions, but Google didn't help我知道这是一个简单的问题,但谷歌没有帮助

When and why should one be used over the other?什么时候以及为什么应该使用一个而不是另一个?

The validates method is a shortcut to all the default validators that Rails provides. validates方法是 Rails 提供的所有默认 验证器的快捷方式。 So, validates :foo, uniqueness: true would trigger UniquenessValidator under the hood.因此, validates :foo, uniqueness: true会在幕后触发UniquenessValidator The source code for validates can be found in the API doc here . validates的源代码可以在此处的 API 文档中找到 As shown there, it basically triggers the validators of the options passed and raises an error in case an invalid option is passed.如图所示,它基本上会触发所传递选项的验证器,并在传递无效选项的情况下引发错误。 validates_uniqueness_of also triggers the UniquenessValidator , the same as validates . validates_uniqueness_of也触发UniquenessValidator ,和validates Its source code is它的源代码是

# File activerecord/lib/active_record/validations/uniqueness.rb, line 233
  def validates_uniqueness_of(*attr_names)
    validates_with UniquenessValidator, _merge_attributes(attr_names)
  end

The only difference is that with validates_uniqueness_of , we can ONLY validate the uniqueness and not pass additional options, whereas validates accepts multiple options.唯一的区别是,使用validates_uniqueness_of ,我们只能验证唯一性而不传递额外的选项,而validates接受多个选项。 So we could have the following validations with validates :因此,我们可以使用validates进行以下验证:

validates :name, presence: true, uniqueness: true, <some other options>

But the same would not be possible with validates_uniqueness_of .但是对于validates_uniqueness_of ,同样是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM