Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate vs validate_uniquess_of?

Is there a difference between using

validates :foo, uniqueness: true

or

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?

like image 673
uno Avatar asked Oct 29 '25 03:10

uno


1 Answers

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

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>

But the same would not be possible with validates_uniqueness_of.

like image 186
Anuj Khandelwal Avatar answered Oct 31 '25 17:10

Anuj Khandelwal