Class: ActiveRecord::Validations::UniquenessValidator

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

Overview

:nodoc:

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ UniquenessValidator

Returns a new instance of UniquenessValidator.

[View source]

6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/active_record/validations/uniqueness.rb', line 6

def initialize(options)
  if options[:conditions] && !options[:conditions].respond_to?(:call)
    raise ArgumentError, "#{options[:conditions]} was passed as :conditions but is not callable. " \
                         "Pass a callable instead: `conditions: -> { where(approved: true) }`"
  end
  unless Array(options[:scope]).all? { |scope| scope.respond_to?(:to_sym) }
    raise ArgumentError, "#{options[:scope]} is not supported format for :scope option. " \
      "Pass a symbol or an array of symbols instead: `scope: :user_id`"
  end
  super
  @klass = options[:class]
  @klass = @klass.superclass if @klass.singleton_class?
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

[View source]

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/active_record/validations/uniqueness.rb', line 20

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

  return if record.persisted? && !validation_needed?(finder_class, record, attribute)

  relation = build_relation(finder_class, attribute, value)
  if record.persisted?
    if finder_class.primary_key
      relation = relation.where.not(finder_class.primary_key => [record.id_in_database])
    else
      raise UnknownPrimaryKey.new(finder_class, "Cannot validate uniqueness for persisted record without primary key.")
    end
  end
  relation = scope_relation(record, relation)

  if options[:conditions]
    conditions = options[:conditions]

    relation = if conditions.arity.zero?
      relation.instance_exec(&conditions)
    else
      relation.instance_exec(record, &conditions)
    end
  end

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

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