Skip to content

Instantly share code, notes, and snippets.

@synth
Created January 19, 2014 21:32
Show Gist options
  • Save synth/8511262 to your computer and use it in GitHub Desktop.
Save synth/8511262 to your computer and use it in GitHub Desktop.
A recursive algorithm for generating nested error messages in rails
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"]}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment