views:

67

answers:

3

I'm building an API for my app and would like to return errors in the XML response that are generated by validation errors.

So say you're registering on the site, right now the validation errors returned might be:

Login has already been taken
Password is too short (minimum is 6 characters)
Email has already been taken

But I'd like to reformat that as:

<errors>
    <error>Login has already been taken</error>
    <error>Password is too short (minimum is 6 characters)</error>
    <error>Email has already been taken</error>
</errors>

So, how would I access the validation error array to do that?

+1  A: 

The model object will have an errors object that you can iterate, some examples in the validations doc.

dbarker
+4  A: 

Rails gives you this functionality by default, i.e.

  user.errors.to_xml

Will give you

=>  <?xml version="1.0" encoding="UTF-8"?>
    <errors>  
     <error>Name can't be blank</error>
     <error>Wiki url can't be blank</error>
     <error>User can't be blank</error>
    </errors>
KandadaBoggu
Oh nice. Totally forgot about to_xml.So, how would I put that in my xml.builder file? I tried just dropping it in to a blank builder file but nothing outputs when I do that.
Shpigford
I don't understand your question. Do you mean you want to dump this to a file? OR you want to add extra tags to the generated XML?
KandadaBoggu
+1  A: 

Call #to_xml on errors method


user = User.new
unless user.valid?
  return user.errors.to_xml
end
shingara