2018-11-08 19:23:39 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2021-03-11 19:13:27 +05:30
|
|
|
# NestedAttributesDuplicates
|
2017-09-10 17:25:29 +05:30
|
|
|
#
|
2018-03-17 18:26:18 +05:30
|
|
|
# This validator is designed for especially the following condition
|
2017-09-10 17:25:29 +05:30
|
|
|
# - Use `accepts_nested_attributes_for :xxx` in a parent model
|
|
|
|
# - Use `validates :xxx, uniqueness: { scope: :xxx_id }` in a child model
|
2021-03-11 19:13:27 +05:30
|
|
|
class NestedAttributesDuplicatesValidator < ActiveModel::EachValidator
|
2017-09-10 17:25:29 +05:30
|
|
|
def validate_each(record, attribute, value)
|
2021-03-11 19:13:27 +05:30
|
|
|
return if child_attributes.any? { |child_attribute| record.errors.include?(:"#{attribute}.#{child_attribute}") }
|
2018-03-27 19:54:05 +05:30
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
if options[:scope]
|
|
|
|
scoped = value.group_by do |variable|
|
|
|
|
Array(options[:scope]).map { |attr| variable.send(attr) } # rubocop:disable GitlabSecurity/PublicSend
|
|
|
|
end
|
|
|
|
scoped.each_value { |scope| validate_duplicates(record, attribute, scope) }
|
|
|
|
else
|
|
|
|
validate_duplicates(record, attribute, value)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2018-12-05 23:21:45 +05:30
|
|
|
# rubocop: disable CodeReuse/ActiveRecord
|
2018-03-17 18:26:18 +05:30
|
|
|
def validate_duplicates(record, attribute, values)
|
2021-03-11 19:13:27 +05:30
|
|
|
child_attributes.each do |child_attribute|
|
|
|
|
duplicates = values.reject(&:marked_for_destruction?).group_by(&:"#{child_attribute}").select { |_, v| v.many? }.map(&:first)
|
2023-01-13 00:05:48 +05:30
|
|
|
next unless duplicates.any?
|
|
|
|
|
|
|
|
error_message = +"have duplicate values (#{duplicates.join(", ")})"
|
|
|
|
error_message << " for #{values.first.send(options[:scope])} scope" if options[:scope] # rubocop:disable GitlabSecurity/PublicSend
|
|
|
|
record.errors.add(attribute, error_message)
|
2017-09-10 17:25:29 +05:30
|
|
|
end
|
|
|
|
end
|
2018-12-05 23:21:45 +05:30
|
|
|
# rubocop: enable CodeReuse/ActiveRecord
|
2021-03-11 19:13:27 +05:30
|
|
|
|
|
|
|
def child_attributes
|
|
|
|
options[:child_attributes] || %i[key]
|
|
|
|
end
|
2017-09-10 17:25:29 +05:30
|
|
|
end
|