Class: Mongoid::Validations::UniquenessValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/mongoid/validations/uniqueness.rb

Overview

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

Examples:

Define the uniqueness validator.


class Person
  include Mongoid::Document
  field :title

  validates_uniqueness_of :title
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



17
18
19
# File 'lib/mongoid/validations/uniqueness.rb', line 17

def klass
  @klass
end

Instance Method Details

#setup(klass) ⇒ Object

Unfortunately, we have to tie Uniqueness validators to a class.

Examples:

Setup the validator.

UniquenessValidator.new.setup(Person)

Parameters:

  • klass (Class)

    The class getting validated.

Since:

  • 1.0.0



27
28
29
# File 'lib/mongoid/validations/uniqueness.rb', line 27

def setup(klass)
  @klass = klass
end

#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
# File 'lib/mongoid/validations/uniqueness.rb', line 43

def validate_each(document, attribute, value)
  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