2011-08-23 14 views
5

默认情况下调用rails.model.to_json我如何定制Rails 3验证错误json输出?

将显示是这样的:

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

相反的消息,我需要生成可服务客户端上使用的一些状态代码:

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

此方法与github api v3错误非常相似 - http://developer.github.com/v3/

我该如何使用Rail S'

+0

另一个类似的问题。 http://stackoverflow.com/questions/5911470/api-errors-customization-for-rails-3-like-github-api-v3。也没有答案= \ –

+0

在这个线程中,rails“响应者”用于实现这一点。 http://stackoverflow.com/questions/5911470/api-errors-customization-for-rails-3-like-github-api-v3 –

回答

0

您的手机型号为JSON工作,你可以修改的方式。例如让我们假设你有一个ActiveRecord型号Contact。您可以覆盖as_json来修改渲染行为。

def Contact < ActiveRecord::Base 

    def as_json 
    hash = super 

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

end 

当然,你也可以产生上Contact甚至在控制器在一个单独的方法的JSON。你只需要稍微改变你的渲染方法。

render @contact.as_my_custom_json 
+0

值是像这样的字符串“不能为空”。可能有一些方法可以获取错误类型而不是消息。 –

+0

错误类型是什么意思?所有验证都会产生相同的错误。关键是导致错误的字段,值是消息。你想在你的例子中的“代码”是什么? – diedthreetimes

+0

如果你不使用“不能空白”的消息,只需在你的模型类中覆盖消息就是你想要的代码。例如,'validates_numercality_of:zip_code,“320”' – diedthreetimes

0

在你的控制器,当渲染输出,你的情况JSON的内容,添加以下内容:

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

希望这有助于

+0

多米尼克,我问过不同的问题。对不起,如果我的问题不清楚。 –

+0

现在仍然不清楚,因为在我的解决方案中,您完全符合您的要求(http://developer.github.com/v3/)。你会有这样的:HTTP/1.1 400错误请求 内容长度:35 {“消息”:“解析JSON的问题”} –

+0

有错误数组的响应。我问这件事。 –