Class: UniqueValuesOnAssociationValidator

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

Instance Method Summary collapse

Instance Method Details

#validate_each(object, attribute, _value) ⇒ Object

rubocop:disable Metrics/AbcSize



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/unique_values_on_association_validator.rb', line 2

def validate_each(object, attribute, _value) # rubocop:disable Metrics/AbcSize
  association = object.association(attribute)
  target = association.target
  child_attribute_name = options.fetch(:attribute)

  return if target.blank?

  values = []
  duplicates = []

  target.each do |child|
    child_attribute_value = child[child_attribute_name]

    if values.include?(child_attribute_value)
      duplicates << child_attribute_value
      child.errors.add(child_attribute_name, options[:message] || :taken)
    end

    values << child_attribute_value
  end

  if duplicates.any?
    object.errors.add(attribute, :hadnt_unique_values, joined_duplicates: duplicates.join(", "), **options)
  end
end