Class: MongoODM::Document::Validations::UniquenessValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/mongo_odm/document/validations/uniqueness_validator.rb

Overview

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

Examples:

Define the uniqueness validator.


class Person
  include MongoODM::Document
  field :title

  validates_uniqueness_of :title
end

Instance Method Summary collapse

Instance Method Details

#setup(klass) ⇒ Object

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



21
22
23
# File 'lib/mongo_odm/document/validations/uniqueness_validator.rb', line 21

def setup(klass)
  @klass = klass
end

#validate_each(document, attribute, value) ⇒ Object

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.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/mongo_odm/document/validations/uniqueness_validator.rb', line 33

def validate_each(document, attribute, value)
  criteria = @klass.find(attribute => unique_search_value(value))
  unless document.new_record?
    criteria = criteria.find(:_id => {'$ne' => document._id})
  end

  Array.wrap(options[:scope]).each do |item|
    criteria = criteria.find(item => document.attributes[item])
  end
  if criteria.first
    document.errors.add(
      attribute,
      :taken,
      options.except(:case_sensitive, :scope).merge(:value => value)
    )
  end
end