Skip to content

Instantly share code, notes, and snippets.

@artemv
Last active May 21, 2022 13:28
Show Gist options
  • Save artemv/4993b128c1a25f06d5d0 to your computer and use it in GitHub Desktop.
Save artemv/4993b128c1a25f06d5d0 to your computer and use it in GitHub Desktop.
Uniqueness validator for has_many associated items with accepts_nested_attributes_for
class NestedAttributesUniquenessValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
value = value.reject(&:_destroy) # let's ignore the items to be destroyed here
unless value.map(&options[:field]).uniq.size == value.size
record.errors[attribute] << "must be unique"
duplicates = value - Hash[value.map{|obj| [obj[options[:field]], obj]}].values
duplicates.each { |obj| obj.errors[options[:field]] << "has already been taken" }
end
end
end
@alexandrule
Copy link

@artemv Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment