Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save BoZhuM/a8078711b2a76c9c7925441398768c6c to your computer and use it in GitHub Desktop.
Save BoZhuM/a8078711b2a76c9c7925441398768c6c 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment