【发布时间】:2020-03-05 09:30:15
【问题描述】:
我是 Ruby 新手,正在尝试构建 API。
我遵循了一个教程,并且能够在调用 API 端点时返回 JSON 响应。
在此示例中,调用的函数引发了我想作为 JSON 响应传递的错误。
my_controller.rb
class MyController < ApplicationController
def getTracklist
begin
importer = #this raises an error
rescue StandardError => e
@response = {
error: e.message,
}
return @response
end
end
end
我的观点是这样的:
getTracklist.json.jbuilder
json.response @response
事情是,
这可行,但将我的响应呈现为
{"response":{"error":"the error message"}}
当我想要它时
{"error":"the error message"}
我尝试将视图更改为
json @response
但它失败了:
ActionView::Template::Error(未定义的方法 `json' for 你的意思是? JSON): 1:json @response
那么我怎样才能“完全”呈现我的响应而不必将其放入属性中?
我在阅读有关 ROR 的资料时也看到有时会使用此代码,我想知道如何在这种情况下使用它:
render json: { error_code:'not_found', error: e.message }, status: :not_found
谢谢!
【问题讨论】:
标签: ruby-on-rails json ruby api