Class: NestedAttributesUniquenessValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
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

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.

Parameters:

  • record (ActiveModel::Model)

    the record being validated

  • attribute (Symbol)

    the collection attribute name

  • value (Array<ActiveModel::Model>)

    the nested collection to check



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(&options[:field]).uniq.size == relevant.size

  record.errors.add attribute, "must be unique"
  duplicates = relevant - relevant.index_by { |obj| obj[options[:field]] }.values
  duplicates.each { |obj| obj.errors.add options[:field], "has already been taken" }
end