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
30
31
32
33
34
35
36
37
# File 'lib/composite_primary_keys/validations/uniqueness.rb', line 4

def validate_each(record, attribute, value)
  finder_class = find_finder_class_for(record)
  table = finder_class.unscoped

  table_name   = record.class.quoted_table_name
  sql, params  = mount_sql_and_params(finder_class, table_name, attribute, value)

  relation = table.where(sql, *params)

  Array.wrap(options[:scope]).each do |scope_item|
    scope_value = record.send(scope_item)
    relation = relation.where(scope_item => scope_value)
  end

  unless record.new_record?
    # CPK
    # TODO : This should be in Arel
    #relation = relation.where("#{record.class.quoted_table_name}.#{record.class.primary_key} <> ?", record.send(:id))
    if record.composite?
      predicate = nil
      record.ids_hash.each do |key, value|
        neq = relation.table[key].not_eq(value)
        predicate = predicate ? predicate.and(neq) : neq
      end
      relation = relation.where(predicate)
    else
      relation = relation.where("#{record.class.quoted_table_name}.#{record.class.primary_key} <> ?", record.send(:id))
    end
  end

  if relation.first
    record.errors.add(attribute, :taken, :default => options[:message], :value => value)
  end
end