14
15
16
17
18
19
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
# File 'lib/active_entity/validations/uniqueness_in_embeds.rb', line 14
def validate_each(record, attribute, association_or_value)
reflection = record.class._reflect_on_association(attribute)
if reflection
return unless reflection.is_a?(ActiveEntity::Reflection::EmbeddedAssociationReflection)
return unless reflection.collection?
end
indexed_attribute =
if reflection
reflection.options[:index_errors] || ActiveEntity::Base.index_nested_attribute_errors
else
options[:index_errors] || true
end
association_or_value =
if reflection
Array.wrap(association_or_value).reject(&:marked_for_destruction?)
else
Array.wrap(association_or_value)
end
return if association_or_value.size <= 1
duplicate_records =
if key.is_a? Symbol
association_or_value.group_by(&key)
elsif key.is_a? Array
association_or_value.group_by { |r| key.map { |attr| r.send(attr) } }
end
.values
.select { |v| v.size > 1 }
.flatten
return if duplicate_records.empty?
duplicate_records.each do |r|
if key.is_a? Symbol
r.errors.add(key, :duplicated, **options)
normalized_attribute = normalize_attribute(attribute, indexed_attribute, association_or_value.index(r), key)
record.errors.import r.errors.where(key).first, attribute: normalized_attribute
elsif key.is_a? Array
key.each do |attr|
r.errors.add(attr, :duplicated, **options)
normalized_attribute = normalize_attribute(attribute, indexed_attribute, association_or_value.index(r), attr)
record.errors.import r.errors.where(key).first, attribute: normalized_attribute
end
end
end
end
|