Class: NestedAttributesUniquenessValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- NestedAttributesUniquenessValidator
- Defined in:
- app/validators/nested_attributes_uniqueness_validator.rb
Overview
Instance Method Summary collapse
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 |
# File 'app/validators/nested_attributes_uniqueness_validator.rb', line 4 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 |