Class: Mongoid::Validations::UniquenessValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- Mongoid::Validations::UniquenessValidator
- Defined in:
- lib/mongoid/validations/uniqueness.rb
Overview
Validates whether or not a field is unique against the documents in the database.
Instance Attribute Summary collapse
-
#klass ⇒ Object
readonly
Returns the value of attribute klass.
Instance Method Summary collapse
-
#setup(klass) ⇒ Object
Unfortunately, we have to tie Uniqueness validators to a class.
-
#validate_each(document, attribute, value) ⇒ Errors
Validate the document for uniqueness violations.
Instance Attribute Details
#klass ⇒ Object (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.
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.
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/mongoid/validations/uniqueness.rb', line 43 def validate_each(document, attribute, value) return unless document.send("attribute_changed?", attribute.to_s) if document. return if skip_validation?(document) relation = document._parent.send(document..name) criteria = relation.where(criterion(document, attribute, value)) criteria = scope(criteria, document, attribute) if document.primary_key == Array.wrap(attribute) if criteria.count > 1 document.errors.add( attribute, :taken, .except(:case_sensitive, :scope).merge(:value => value) ) end else if criteria.exists? document.errors.add( attribute, :taken, .except(:case_sensitive, :scope).merge(:value => value) ) end end else criteria = klass.where(criterion(document, attribute, value)) criteria = scope(criteria, document, attribute) document.errors.add(attribute, :taken, .except(:case_sensitive, :scope).merge(:value => value)) if criteria.exists? end end |