Skip to content

Instantly share code, notes, and snippets.

@artemv
Last active May 21, 2022 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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
@artemv
Copy link
Author

artemv commented Mar 17, 2016

Based on http://stackoverflow.com/a/9183308/948899, take a look to get a context/use case info

@alexandrule
Copy link

@artemv Thanks!

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