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 Method Summary collapse
-
#setup(klass) ⇒ Object
Unfortunately, we have to tie Uniqueness validators to a class.
-
#validate_each(document, attribute, value) ⇒ Object
Validate the document for uniqueness violations.
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.
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. 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([:scope]).each do |item| criteria = criteria.where(item => document.attributes[item.to_s]) end if criteria.exists? document.errors.add( attribute, :taken, .except(:case_sensitive, :scope).merge(:value => value) ) end end |