【发布时间】:2016-02-15 17:41:12
【问题描述】:
我确定我在这里有一个基本的rescue_from 问题,但是当我的Validation 失败但我似乎无法弄清楚时引发异常时,我试图获得所需的输出。
目前我的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
虽然这是我想要的,但我必须去每个控制器并添加它,但这不是 DRY 方法...我宁愿将它集中在 ApplicationController
感谢任何帮助。 谢谢!
我已经检查了Correct JSON format & How can I “Pretty” format my JSON output in Ruby on Rails?
【问题讨论】:
标签: ruby json ruby-on-rails-4