Class: Hydra::Validations::UniquenessValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/hydra/validations/uniqueness.rb

Overview

UniquenessValidator - an ActiveFedora model validator

Usage:

validates :field, uniqueness: { solr_name: "field_ssim" }
validates_uniqueness_of :field, solr_name: "field_ssim"

Restrictions:

  • Accepts only one attribute (can have more than one UniquenessValidator on a model, however)

  • :solr_name option must be present

  • Can be used on enumerable values (attribute defined with :multiple=>true option), but validator also validates single cardinality, so will not pass validation if enumerable has more than one member.

CAVEAT: The determination of uniqueness depends on a Solr query. False negatives (record invalid) may result if, for example, querying a Solr field of type “text”.

Instance Method Summary collapse

Instance Method Details

#check_validity!Object



27
28
29
30
31
32
33
34
# File 'lib/hydra/validations/uniqueness.rb', line 27

def check_validity!
  if attributes.length > 1 
    raise ArgumentError, "UniquenessValidator accepts only a single attribute: #{attributes}" 
  end
  unless options[:solr_name].present?
    raise ArgumentError, "UniquenessValidator requires the :solr_name option be present." 
  end
end

#validate_each(record, attribute, value) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/hydra/validations/uniqueness.rb', line 36

def validate_each(record, attribute, value)
  wrapped_value = Array.wrap(value)
  if wrapped_value.length > 1
    record.errors.add(attribute, "can't have more than one value") 
  elsif wrapped_value.empty? 
    record.errors.add(attribute, "can't be empty") unless options[:allow_empty]
  else
    conditions = {options[:solr_name] => wrapped_value.first}
    conditions.merge!("-id" => record.id) if record.persisted?
    record.errors.add attribute, "has already been taken" if record.class.exists?(conditions)
  end
end