class Rethinker::Document::Validation::UniquenessValidator
Public Instance Methods
apply_scopes(finder, document)
click to toggle source
# File lib/rethinker/document/validation.rb, line 51 def apply_scopes(finder, document) Array.wrap(options[:scope]).each do |scope_item| finder = finder.where{|doc| doc[scope_item.to_s].eq(document.attributes[scope_item.to_s])} end finder end
exclude_document(finder, document)
click to toggle source
# File lib/rethinker/document/validation.rb, line 58 def exclude_document(finder, document) finder.where{|doc| doc["id"].ne(document.attributes["id"])} end
validate_each(document, attribute, value)
click to toggle source
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 [ Boolean ] true if the attribute is unique.
# File lib/rethinker/document/validation.rb, line 40 def validate_each(document, attribute, value) finder = document.class.where(attribute => value) finder = apply_scopes(finder, document) finder = exclude_document(finder, document) if document.persisted? is_unique = finder.count == 0 unless is_unique document.errors.add(attribute, 'is already taken') end is_unique end