Class: NestedAttributesUniquenessValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/nested_attributes_uniqueness_validator.rb

Defined Under Namespace

Classes: MissingScopeError

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Raises:



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

def validate_each(record, attribute, value)
  parsed_options = parse_options(record)
  scope = [parsed_options[:scope]].flatten.compact

  raise MissingScopeError if scope.empty?

  unless parsed_options[:allow_destroyed] == true
    value = value.reject(&:marked_for_destruction?)
  end

  same_object = value.detect do |object|
    value.select do |obj|
      scope.map do |scope_attribute|
        a = obj.send(scope_attribute)
        b = object.send(scope_attribute)

        if parsed_options[:allow_blank] == true
          (a == b)
        else
          (a.present? || b.present?) && (a == b)
        end
      end.all?
    end.count > 1
  end

  return unless same_object.present?

  same_object.errors.add(
    parsed_options[:attribute].presence || scope.first,
    parsed_options[:message].presence || :taken
  )
  record.errors.add(attribute, parsed_options[:message].presence || :invalid)
end