Class: NestedAttributesUniquenessValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- NestedAttributesUniquenessValidator
- Defined in:
- app/validators/nested_attributes_uniqueness_validator.rb
Overview
Validates that a nested attributes collection contains no duplicate values
for a given field. Records marked for destruction are ignored.
From http://stackoverflow.com/questions/5482777/rails-3-uniqueness-validation-for-nested-fields-for
Instance Method Summary collapse
-
#validate_each(record, attribute, value) ⇒ void
Validates that no two members of the collection share the same field value.
Instance Method Details
#validate_each(record, attribute, value) ⇒ void
This method returns an undefined value.
Validates that no two members of the collection share the same field value.
14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'app/validators/nested_attributes_uniqueness_validator.rb', line 14 def validate_each(record, attribute, value) # Ignore items already marked for destruction — they will not be saved, # so they cannot collide with the survivors. (Matches the standard Rails # idiom for nested attributes; lets callers `mark_for_destruction` a # duplicate to dedupe without tripping this validator.) relevant = value.reject(&:marked_for_destruction?) return if relevant.map(&[:field]).uniq.size == relevant.size record.errors.add attribute, "must be unique" duplicates = relevant - relevant.index_by { |obj| obj[[:field]] }.values duplicates.each { |obj| obj.errors.add [:field], "has already been taken" } end |