Class: Ricordami::UniqueValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/ricordami/unique_validator.rb

Instance Method Summary collapse

Instance Method Details

#setup(klass) ⇒ Object



21
22
23
# File 'lib/ricordami/unique_validator.rb', line 21

def setup(klass)
  attributes.each { |attribute| klass.index :unique => attribute, :scope => options[:scope] }
end

#validate_each(record, attribute, value) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/ricordami/unique_validator.rb', line 5

def validate_each(record, attribute, value)
  return true unless record.new_record? || record.send(:attribute_changed?, attribute)
  index_name = "u_#{attribute}".to_sym
  index = record.class.indices[index_name]
  if index.scope
    scope_values = index.scope.map { |field| record.send(field) }
    value = index.normalize_value([value].push(*scope_values))
  end
  if index.include?(value)
    attr_def = record.class.attributes[attribute]
    unless record.persisted? && attr_def.read_only?
      record.errors.add(attribute, options[:message] || "is already used")
    end
  end
end