Class: ActiveModel::Validations::ArrayValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/active_model/validations/array_validator.rb

Overview

Based on gist.github.com/ssimeonov/6519423

Validates the values of an Array with other validators. Generates error messages that include the index and value of invalid elements.

Example:

validates :values, array: { presence: true, inclusion: { in: %w{ big small } } }

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#attributeObject (readonly)

Returns the value of attribute attribute.



16
17
18
# File 'lib/active_model/validations/array_validator.rb', line 16

def attribute
  @attribute
end

#proxy_attributeObject (readonly)

Returns the value of attribute proxy_attribute.



16
17
18
# File 'lib/active_model/validations/array_validator.rb', line 16

def proxy_attribute
  @proxy_attribute
end

#recordObject (readonly)

Returns the value of attribute record.



16
17
18
# File 'lib/active_model/validations/array_validator.rb', line 16

def record
  @record
end

Instance Method Details

#validate_each(record, attribute, values) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/active_model/validations/array_validator.rb', line 18

def validate_each(record, attribute, values)
  @record = record
  @attribute = attribute

  # Cache any existing errors temporarily.
  @existing_errors = record.errors.delete(attribute) || []

  # Run validations
  validate_each_internal values

  # Restore any existing errors.
  return if @existing_errors.blank?

  @existing_errors.each { |e| record.errors.add attribute, e }
end