Class: ActiveRecord::Validations::UniquenessValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/composite_primary_keys/validations/uniqueness.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/composite_primary_keys/validations/uniqueness.rb', line 4

def validate_each(record, attribute, value)
  finder_class = find_finder_class_for(record)
  value = map_enum_attribute(finder_class, attribute, value)

  relation = build_relation(finder_class, attribute, value)
  if record.persisted?
    # CPK
    if finder_class.primary_key.is_a?(Array)
      predicate = finder_class.cpk_id_predicate(finder_class.arel_table, finder_class.primary_key, record.id_in_database || record.id)
      relation = relation.where.not(predicate)
    elsif finder_class.primary_key
      relation = relation.where.not(finder_class.primary_key => record.id_in_database)
    else
      raise UnknownPrimaryKey.new(finder_class, "Can not validate uniqueness for persisted record without primary key.")
    end
  end
  relation = scope_relation(record, relation)
  relation = relation.merge(options[:conditions]) if options[:conditions]

  if relation.exists?
    error_options = options.except(:case_sensitive, :scope, :conditions)
    error_options[:value] = value

    record.errors.add(attribute, :taken, error_options)
  end
end