Class: MiniForm::NestedValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/mini_form/nested_validator.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, _, relation) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/mini_form/nested_validator.rb', line 7

def validate_each(record, _, relation)
  return if relation.valid?

  if record.errors.respond_to?(:merge!)
    # Rails 6.1+ where accessing ActiveModel::Errors as a hash has been
    # deprecated and the errors array is frozen. For this reason we use the new
    # method merge!() which appends the errors as NestedErrors to the array. "This is the way."
    record.errors.merge!(relation.errors)
    return
  end

  # Rails < 6.1
  relation.errors.each do |name, value|
    record.errors.add name, value
  end
end