我敢肯定,我有一个基本的rescue_from
问题在这里,但是,我试图得到所需的输出,当我的Validation
失败时引发异常,但我似乎无法数字出来。如何渲染正确的JSON格式与提出的错误
目前我ApplicationController
如下:
class ApplicationController < ActionController::API
include ActionController::Serialization
rescue_from ActiveRecord::RecordInvalid do |e|
render json: {error: e.message}, status: 404
end
end
和JSON输出我得到的是:
{
"error": "Validation failed: Organization can't be blank, Description can't be blank, Artwork can't be blank, Language code can't be blank, Copyright can't be blank, Right to left is not included in the list, Digital audio is not included in the list, Portion is not included in the list, Electronic text is not included in the list, Old is not included in the list, New is not included in the list"
}
所需的输出中我想获得(或类似的东西)如下:
{
"organization_id": [
"can't be blank"
],
"description": [
"can't be blank"
],
"artwork": [
"can't be blank"
],
"language_code": [
"can't be blank"
],
"copyright": [
"can't be blank"
],
"right_to_left": [
"is not included in the list"
],
"digital_audio": [
"is not included in the list"
],
"portion": [
"is not included in the list"
],
"electronic_text": [
"is not included in the list"
],
"old": [
"is not included in the list"
],
"new": [
"is not included in the list"
]
}
我不知道如何得到这个。我是说我注释掉ApplicationController
的rescue_from
方法和设置我的RecordController
创建方法是这样期望的输出:
def create
r = Record.create(record_params)
r.save
if r.save
render json: r
else
render json: r.errors
end
end
虽然这是我想要的,我会去到每一个控制器和添加此但这不会是干的方法...我宁愿集中在ApplicationController
任何帮助表示赞赏。 谢谢!
我已经检查Correct JSON format & How can I “Pretty” format my JSON output in Ruby on Rails?
我试图防止自己不必添加代码,每个控制器和行动返回几个不同的键链接的规范。用你的方法,我必须这样做。这就是我只想向'ApplicationController'添加代码的原因。 – Awatatah
没有尝试解析Exceptions消息,我不知道如何获得与对象本身返回的格式相同的格式。 –