Class: DuckRecord::Validations::UniquenessOnRealRecordValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/duck_record/validations/uniqueness_on_real_record.rb

Overview

:nodoc:

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ UniquenessOnRealRecordValidator

Returns a new instance of UniquenessOnRealRecordValidator.



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
# File 'lib/duck_record/validations/uniqueness_on_real_record.rb', line 4

def initialize(options)
  unless defined?(ActiveRecord)
    raise NameError, "Not found Active Record."
  end

  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

  @finder_class = if options[:class_name].present?
                    options[:class_name].safe_constantize
                  elsif options[:class].present? && options[:class].is_a?(Class)
                    options[:class]
                  else
                    nil
                  end

  unless @finder_class
    raise ArgumentError, "Must provide one of option :class_name or :class."
  end
  unless @finder_class < ActiveRecord::Base
    raise ArgumentError, ":class must be an Active Record model, but got #{@finder_class}."
  end
  if @finder_class.abstract_class?
    raise ArgumentError, ":class can't be an abstract class."
  end

  @primary_key = options[:primary_key]

  super({ case_sensitive: true }.merge!(options))
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/duck_record/validations/uniqueness_on_real_record.rb', line 37

def validate_each(record, attribute, value)
  table = @finder_class.arel_table
  value = map_enum_attribute(@finder_class, attribute, value)

  relation = build_relation(@finder_class, table, attribute, value)
  if @primary_key.present? && record.respond_to?(@primary_key)
    if @finder_class.primary_key
      relation = relation.where.not(@finder_class.primary_key => record.send(@primary_key))
    else
      raise ActiveRecord::UnknownPrimaryKey.new(@finder_class, "Can not validate uniqueness for persisted record without primary key.")
    end
  end
  relation = scope_relation(record, table, 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