我敢肯定,我有一個基本的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消息,我不知道如何獲得與對象本身返回的格式相同的格式。 –