5

By default calling rails.model.to_json

Will display something like this:

{"name":["can't be blank"],"email":["can't be blank"],"phone":["can't be blank"]}

Instead of message i need to generate some status code that could be used on service client:

[{"field": "name", "code": "blank"}, {"field": "email", "code": "blank"}]

This approach is very similar to github api v3 errors - http://developer.github.com/v3/

How can I achieve this with Rails?

Alexey Zakharov
  • 24,694
  • 42
  • 126
  • 197
  • Another similar question. http://stackoverflow.com/questions/5911470/api-errors-customization-for-rails-3-like-github-api-v3. Also with no answer =\ – Alexey Zakharov Aug 23 '11 at 08:40
  • In this thread, rails "Responders" are used to achive that. http://stackoverflow.com/questions/5911470/api-errors-customization-for-rails-3-like-github-api-v3 – Alexey Zakharov Nov 05 '11 at 18:14

2 Answers2

0

In your controller, when you render the output, in your case JSON content, add the following :

render :json => @yourobject, :status => 422 # or whatever status you want.

Hope this helps

Dominic Goulet
  • 7,983
  • 7
  • 28
  • 56
  • Dominic, I have asked about different problem. Sorry if my question wasn't clear. – Alexey Zakharov Aug 23 '11 at 17:53
  • And it is still unclear, because with my solution you have exactly what you asked for (http://developer.github.com/v3/). You will have something like : HTTP/1.1 400 Bad Request Content-Length: 35 {"message":"Problems parsing JSON"} – Dominic Goulet Aug 24 '11 at 11:47
0

On your model you can modify the way as json operates. For instance let us assume you have a ActiveRecord model Contact. You can override as_json to modify the rendering behavior.

def Contact < ActiveRecord::Base

  def as_json
    hash = super

    hash.collect {|key, value|
      {"field" => key, "code" => determine_code_from(value)} 
    }
  end

end

Of course, you could also generate the json in a separate method on Contact or even in the controller. You would just have to alter your render method slightly.

render @contact.as_my_custom_json
diedthreetimes
  • 4,086
  • 26
  • 38
  • Value is string like this "Can't be blank". May there is some way to get error type instead of message. – Alexey Zakharov Aug 24 '11 at 11:52
  • What do you mean by error type? All validations raise the same error. The key is the field that is causing the error, and the value is the message. What do you want the "code" in your example to be? – diedthreetimes Aug 24 '11 at 18:18
  • If you don't use the "Can't be blank" message for anything else, simply override the message in your model class to be what you want the code to be. For example, `validates_numercality_of :zip_code, "320"` – diedthreetimes Aug 24 '11 at 18:20
  • Hmm... overriding message in declaration is good idea! I need this to implement api and it should work. – Alexey Zakharov Aug 25 '11 at 16:18