Warning: Creating default object from empty value in /homepages/39/d161420129/htdocs/p373.net/wp/wp-content/themes/p373b/admin/functions.php on line 183
Recursively generate nested errors in json with Rails

Recursively generate nested errors in json with Rails

See this gist: https://gist.github.com/synth/8511262

    def nice_errors(object, errors)
      object.errors.each do |key|
        error_obj = object.send(key)
        if error_obj.kind_of?(Array)
          errors[key] = {}
          error_obj.each {|item| nice_errors(item, errors[key])}
        elsif error_obj.kind_of?(ActiveRecord::Base)
          errors[error_obj.id] = {}
          nice_errors(error_obj, errors[error_obj.id])
        else
          errors[key] = object.errors[key]
        end
      end
      return errors
    end
  end

  # call it with
  nice_errors(resource, {})

  # will generate something like:
  {"errors":{"user_recipients":{"email":["may not be the same as your own email"]}}}
    This entry was posted in Coding, Ruby/Rails, Technology. Bookmark the permalink. Both comments and trackbacks are currently closed.