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 Method Summary collapse

Instance Method Details

#setup(klass) ⇒ Object

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



19
20
21
# File 'lib/mongoid/validations/uniqueness.rb', line 19

def setup(klass)
  @klass = klass
end

#validate_each(document, attribute, value) ⇒ Object

TODO:

Durran: This method needs refactoring.

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
50
51
52
53
54
55
56
57
# File 'lib/mongoid/validations/uniqueness.rb', line 33

def validate_each(document, attribute, value)
  if document.embedded?
    return if document._parent.nil?
    criteria = document._parent.send(document..name)
    # If the parent document embeds_one, no need to validate uniqueness
    return if criteria.is_a?(Mongoid::Document)
    criteria = criteria.where(attribute => unique_search_value(value), :_id => {'$ne' => document._id})
  else
    criteria = @klass.where(attribute => unique_search_value(value))
    unless document.new_record?
      criteria = criteria.where(:_id => {'$ne' => document._id})
    end
  end

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