Validates whether or not a field is unique against the documents in the database.
@example Define the uniqueness validator.
class Person include Mongoid::Document field :title validates_uniqueness_of :title end
Unfortunately, we have to tie Uniqueness validators to a class.
@example Setup the validator. UniquenessValidator.new.setup(Person)
@param [ Class ] klass The class getting validated.
@since 1.0.0
# File lib/mongoid/validations/uniqueness.rb, line 28 def setup(klass) @klass = klass end
Validate the document for uniqueness violations.
@example Validate the document.
validate_each(person, :title, "Sir")
@param [ Document ] document The document to validate. @param [ Symbol ] attribute The field to validate on. @param [ Object ] value The value of the field.
@return [ Errors ] The errors.
@since 1.0.0
# File lib/mongoid/validations/uniqueness.rb, line 44 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