Last active
May 21, 2022 13:28
-
-
Save artemv/4993b128c1a25f06d5d0 to your computer and use it in GitHub Desktop.
Uniqueness validator for has_many associated items with accepts_nested_attributes_for
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on http://stackoverflow.com/a/9183308/948899, take a look to get a context/use case info