Skip to content

Instantly share code, notes, and snippets.

@francirp
Last active May 21, 2022 13:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save francirp/01d2b82c3000cce626f0f34bdcf5c33c to your computer and use it in GitHub Desktop.
Save francirp/01d2b82c3000cce626f0f34bdcf5c33c to your computer and use it in GitHub Desktop.
Validate Uniqueness of Nested Attributes in Rails - Custom Validator
class NestedAttributesUniquenessValidator < ActiveModel::EachValidator
def validate_each(record, attribute, items)
items = items.reject(&:_destroy) # let's ignore the items to be destroyed here
unless items.map(&options[:field]).to_a.uniq.size == items.size
record.errors[attribute] << "must be unique"
field = options[:field]
values = items.map {|item| item.send(field) }
duplicates = items.find_all {|item| values.count(item.send(field)) > 1 && item.id.nil? }
duplicates.each { |obj| obj.errors[field] << "has already been taken" }
end
end
end
# example implementation of custom validator on active record:
class Zebra < ActiveRecord::Base
validates :stripes, nested_attributes_uniqueness: { field: :my_unique_field }
end
@francirp
Copy link
Author

Tweaked code from a solution in this stackoverflow question: http://stackoverflow.com/questions/5482777/rails-3-uniqueness-validation-for-nested-fields-for

@alexandrule
Copy link

@francirp Thanks!

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