Flowdock
method

validates_uniqueness_of

Importance_3
v2.3.8 - Show latest stable - 1 note - Class: ActiveModel::Validations::ClassMethods
validates_uniqueness_of(*attr_names) public

Validates whether the value of the specified attributes are unique across the system. Useful for making sure that only one user can be named "davidhh".

  class Person < ActiveRecord::Base
    validates_uniqueness_of :user_name, :scope => :account_id
  end

It can also validate whether the value of the specified attributes are unique based on multiple scope parameters. For example, making sure that a teacher can only be on the schedule once per semester for a particular class.

  class TeacherSchedule < ActiveRecord::Base
    validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
  end

When the record is created, a check is performed to make sure that no record exists in the database with the given value for the specified attribute (that maps to a column). When the record is updated, the same check is made but disregarding the record itself.

Because this check is performed outside the database there is still a chance that duplicate values will be inserted in two parallel transactions. To guarantee against this you should create a unique index on the field. See add_index for more information.

Configuration options:

  • :message - Specifies a custom error message (default is: "has already been taken")
  • :scope - One or more columns by which to limit the scope of the uniqueness constraint.
  • :case_sensitive - Looks for an exact match. Ignored by non-text columns (true by default).
  • :allow_nil - If set to true, skips this validation if the attribute is nil (default is: false)
  • :allow_blank - If set to true, skips this validation if the attribute is blank (default is: false)
  • :if - Specifies a method, proc or string to call to determine if the validation should occur (e.g. :if =&gt; :allow_validation, or :if =&gt; Proc.new { |user| user.signup_step &gt; 2 }). The method, proc or string should return or evaluate to a true or false value.
  • :unless - Specifies a method, proc or string to call to determine if the validation should not occur (e.g. :unless =&gt; :skip_validation, or :unless =&gt; Proc.new { |user| user.signup_step &lt;= 2 }). The method, proc or string should return or evaluate to a true or false value.
Show source
Register or log in to add new notes.
July 1, 2008
3 thanks

:case_sensitive is on by default?

In contrast to what the documentation said, :case_sensitive seems to be on by default. This is the case with MySQL at least, I’m not sure about other databases.