Class: Mongoid::Validatable::UniquenessValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Includes:
Queryable
Defined in:
build/mongoid-master/lib/mongoid/validatable/uniqueness.rb

Overview

Validates whether or not a field is unique against the documents in the database.

It is also possible to limit the uniqueness constraint to a set of records matching certain conditions:

class Person
  include Mongoid::Document
  field :title
  field :active, type: Boolean

  validates_uniqueness_of :title, conditions: -> {where(active: true)}
end

Examples:

Define the uniqueness validator.


class Person
  include Mongoid::Document
  field :title

  validates_uniqueness_of :title
end

Instance Method Summary collapse

Methods included from Queryable

#with_query

Instance Method Details

#validate_each(document, attribute, value) ⇒ Errors

Validate the document for uniqueness violations.

Examples:

Validate the document.

validate_each(person, :title, "Sir")

Parameters:

  • document (Document)

    The document to validate.

  • attribute (Symbol)

    The field to validate on.

  • value (Object)

    The value of the field.

Returns:

Since:

  • 1.0.0



43
44
45
46
47
48
49
50
51
52
53
# File 'build/mongoid-master/lib/mongoid/validatable/uniqueness.rb', line 43

def validate_each(document, attribute, value)
  with_query(document) do
    attrib, val = to_validate(document, attribute, value)
    return unless validation_required?(document, attrib)
    if document.embedded?
      validate_embedded(document, attrib, val)
    else
      validate_root(document, attrib, val)
    end
  end
end