Forked from artemv/nested_attributes_uniqueness_validator.rb
Created
November 2, 2016 13:01
-
-
Save BoZhuM/a8078711b2a76c9c7925441398768c6c to your computer and use it in GitHub Desktop.
Uniqueness validator for has_many associated items with accepts_nested_attributes_for
This file contains 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