Class: Caprese::Record::AssociatedValidator

Inherits:
ActiveRecord::Validations::AssociatedValidator
  • Object
show all
Defined in:
lib/caprese/record/associated_validator.rb

Overview

Note:

BEFORE

Note:

AFTER

Formats nested errors on associations in a more useful way than Rails alone

POST /posts (with invalid resources) =>

[
  { "key"=>"invalid", "field"=>"attachment", "message"=>"Attachment is invalid." }
]

POST /posts (with invalid resources) =>

[
  { "key"=>"not_found", "field"=>"attachment.file", "message"=>"Could not find a file at ..."}
]

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/caprese/record/associated_validator.rb', line 17

def validate_each(record, attribute, value)
  if Caprese::Record.caprese_style_errors
    Array(value).reject { |r| r.marked_for_destruction? || r.valid? }.each do |invalid_record|
      invalid_record.errors.to_a.each do |error|
        field_name = error.field ? "#{attribute}.#{error.field}" : attribute
        record.errors.add(field_name, error.code, { t: error.t }.merge(value: invalid_record))
      end
    end
  else
    super
  end
end