Class: ActiveRecord::Validations::UniquenessValidator

Inherits:
ActiveModel::EachValidator show all
Defined in:
activerecord/lib/active_record/validations/uniqueness.rb

Instance Attribute Summary

Attributes inherited from ActiveModel::EachValidator

#attributes

Attributes inherited from ActiveModel::Validator

#options

Instance Method Summary (collapse)

Methods inherited from ActiveModel::EachValidator

#check_validity!, #validate

Methods inherited from ActiveModel::Validator

kind, #kind, #validate

Constructor Details

- (UniquenessValidator) initialize(options)

A new instance of UniquenessValidator



6
7
8
# File 'activerecord/lib/active_record/validations/uniqueness.rb', line 6

def initialize(options)
  super(options.reverse_merge(:case_sensitive => true))
end

Instance Method Details

- (Object) setup(klass)

Unfortunately, we have to tie Uniqueness validators to a class.



11
12
13
# File 'activerecord/lib/active_record/validations/uniqueness.rb', line 11

def setup(klass)
  @klass = klass
end

- (Object) validate_each(record, attribute, value)



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'activerecord/lib/active_record/validations/uniqueness.rb', line 15

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?
    # TODO : This should be in Arel
    relation = relation.where("#{record.class.quoted_table_name}.#{record.class.primary_key} <> ?", record.send(:id))
  end

  if relation.exists?
    record.errors.add(attribute, :taken, options.except(:case_sensitive, :scope).merge(:value => value))
  end
end