Class: ActiveStash::Validations::UniquenessValidator

Inherits:
ActiveRecord::Validations::UniquenessValidator
  • Object
show all
Defined in:
lib/active_stash/validations.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Uniqueness validator for encrypted fields.

It relies on an exact index being present for the attribute (created by default with `stash_index`)

It's worth pointing out that this validation does not care of there is a unique index on that field within the collection. This mirrors how ActiveRecord works, which does not care if there is a unique index on the field in the database in order for validates_uniqueness_of to work.



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/active_stash/validations.rb', line 24

def validate_each(record, attribute, value)
  indexes_on_attribute = record.class.stash_indexes.on(attribute).select{|idx| [:exact, :range].include?(idx.type)}

  if indexes_on_attribute.length > 0
    result = record.class.query(attribute => value).first

    if (options[:case_sensitive] && result[attribute] == attribute) || result
      record.errors.add(attribute, options[:message] || "already exists")
    end
  else
    super
  end
end