Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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