验证与validate_uniquess_of?

uno*_*uno 1 ruby-on-rails

使用之间有区别吗

validates :foo, uniqueness: true

要么

validates_uniqueness_of :foo

我知道这是一个简单的问题,但Google没有帮助

什么时候以及为什么要使用另一个?

Anu*_*wal 6

The validates method is a shortcut to all the default validators that Rails provides. So, validates :foo, uniqueness: true would trigger UniquenessValidator under the hood. The source code for validates can be found in the API doc here. 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. 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
Run Code Online (Sandbox Code Playgroud)

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. So we could have the following validations with validates:

validates :name, presence: true, uniqueness: true, <some other options>
Run Code Online (Sandbox Code Playgroud)

But the same would not be possible with validates_uniqueness_of.