rails/rails — Issue #3269: respond_with returns wrong JSON content for errors + AResource documentation bugs
Author: NoICE
Created: 2011-10-09 14:21:01+00:00
State: open

Hi,

I have this piece of code in my API controller:

``` ruby
respond_to :xml, :json
def create
#....
respond_with(@item, :location => nil)
end
```

When ActiveResource client posts data to this and it fails because of the validation errors,
it produces nice XML which is properly parsed nad ActiveResource model knows what errors are triggered.

But for JSON format, it produces this:

``` json
{
"name": [
"Name cannot be empty"
]
}
```

According to documentation, it should be under "errors" key.
I thought I can override this behavior by custom format handling, like so:

``` ruby
respond_with(@item, :location => nil) do |format|
format.json { render :json => { "errors" => @item.errors } }
format.xml { render :xml => @item.errors }
end
```

But this doesn't work either, because when there are some errors on the model, it just simply ignores the &block and returns that damn wrong json again.

So, only one possible fix for me for now is this, which is UGLY (a big contrast to one-line respond_with).

``` ruby
if @item.valid? && @item.persisted?
respond_with(@item, :location => url_for([:api, @item]))
else
respond_to do |format|
format.json { render :json => { "errors" => @item.errors }, :status => :unprocessable_entity }
format.xml { render :xml => @item.errors, :status => :unprocessable_entity }
end
end
```

BTW there is also bug in documentation for ActiveResource which states that the resulting JSON should be Array of error messages, but it needs to be Hash, else ActiveResource throws one error after another.

```
# Response (422):
# First cannot be empty
# or
# {"errors":["First cannot be empty"]}
#
```

This is wrong, as it expects { "errors": { "name": ["Name cannot be empty"] } }.
There is also pull request for this to patch the tests, but documentation remains in old state.
https://github.com/odorcicd/rails/commit/b09b2a8401c18d1efff21b3919ac280470a6eb8b

Also, as a side note, why AResource expects XML formated as an array and JSON formated as a Hash?

Too many questions in a single issue, I know.
If I just missed something and I do it wrong, let me know.