Sha256: 6316a55dcd21e6d9167d11fc5c66c95a8d83b83376acb2bc10ca3346378194cd

Contents?: true

Size: 1.78 KB

Versions: 3

Compression:

Stored size: 1.78 KB

Contents

module Fields
  module Serializer
    module ActiveRecord

      module Errors
        # 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.
        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

        private

        #   {  "xxx-xxxxxxxx-xxx-xxxxxx" => { name: ["can't be blank"], age: ["can't be less than 18"] },
        #                            "0" => { name: ["can't be blank"], age: ["can't be less than 18"] },
        def __associate_errors(associate)
          Array(associate).map.with_index { |object, i| [object.id || i, object.errors.to_h] }.to_h
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
fields-serializer-0.9.0 lib/fields/serializer/active_record/errors.rb
fields-serializer-0.8.5 lib/fields/serializer/active_record/errors.rb
fields-serializer-0.8.4 lib/fields/serializer/active_record/errors.rb