Module: Fields::Serializer::ActiveRecord::Errors

Included in:
Fields::Serializer::ActiveRecord
Defined in:
lib/fields/serializer/active_record/errors.rb

Instance Method Summary collapse

Instance Method Details

#deep_errors(*association_keys) ⇒ Object

Return a hash with errors of the model merged with errors of the given associated models.

{
  name: ["can't be blank"],
  age:  ["must be greater than 18"],
  cars: {
    "xxx-xxxxxxxx-xxx-xxxxxx" => {
      make: ["can't be blank"],
      type: ["can't be blank"]
    },
    "0" => {
      make: ["can't be blank"],
      year: ["must be greater than 1800"]
    }
    "1" => {
      year: ["must be greater than 1800"]
    }
  }
}

where "xxx-xxxxxxxx-xxx-xxxxxx" is the id of an associated model and
      an incremental integer id is given to those associated models with empty id.
      Similar to ActiveRecord nested attributes notation.


29
30
31
32
33
34
35
36
# File 'lib/fields/serializer/active_record/errors.rb', line 29

def deep_errors(*association_keys)
  association_keys.inject(errors.to_h) do |error_tree, association_key|
    associate = send(association_key)
    next(error_tree) unless associate
    associate = associate.to_a if self.class.reflections[association_key.to_s].collection?
    error_tree.merge!(association_key => __associate_errors(associate))
  end
end