Last active
May 21, 2022 13:27
-
-
Save francirp/01d2b82c3000cce626f0f34bdcf5c33c to your computer and use it in GitHub Desktop.
Validate Uniqueness of Nested Attributes in Rails - Custom Validator
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, 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 |
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
# example implementation of custom validator on active record: | |
class Zebra < ActiveRecord::Base | |
validates :stripes, nested_attributes_uniqueness: { field: :my_unique_field } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tweaked code from a solution in this stackoverflow question: http://stackoverflow.com/questions/5482777/rails-3-uniqueness-validation-for-nested-fields-for