[英]Ruby API response view : how can I render a JSON response?
I'm new to Ruby, trying to building an API.我是 Ruby 新手,正在尝试构建 API。
I've followed a tutorial and was able to return a JSON response when calling an API endpoint.我遵循了一个教程,并且能够在调用 API 端点时返回 JSON 响应。
In this example, the function called raises an error that I want to pass as a JSON response.在此示例中,调用的函数引发了一个错误,我想将其作为 JSON 响应传递。
class MyController < ApplicationController
def getTracklist
begin
importer = #this raises an error
rescue StandardError => e
@response = {
error: e.message,
}
return @response
end
end
end
my view look like this :我的观点是这样的:
json.response @response
this works but renders my response as这有效,但使我的反应为
{"response":{"error":"the error message"}}
while I want it as虽然我想要它
{"error":"the error message"}
I made an attempts by changing my view to我尝试通过将视图更改为
json @response
but it fails :但它失败了:
ActionView::Template::Error (undefined method `json' for <#:0x0000559304675470> Did you mean? JSON): 1: json @response
ActionView::Template::Error (未定义方法`json' for <#:0x0000559304675470> 你是说吗?JSON): 1: json @response
So how could I render my response "fully" without having to put it in a property ?那么如何在不必将其放入属性的情况下“完全”呈现我的响应?
I've also seen when reading stuff about ROR that this code is sometimes used, and I was wondering how I could use it in this situation :我在阅读有关 ROR 的内容时也看到有时会使用此代码,我想知道如何在这种情况下使用它:
render json: { error_code:'not_found', error: e.message }, status: :not_found
Thanks !谢谢 !
There are multiple ways of achieving what you want.有多种方法可以实现您想要的。 You could
merge!
你可以
merge!
the response into the jbuilder root.响应到 jbuilder 根。
json.merge! @response
The above merges all key/value-pairs into the jbuilder root.以上将所有键/值对合并到 jbuilder 根目录中。 You could also opt to
extract!
您也可以选择
extract!
specific attributes.具体属性。
json.extract! @response, :error
Alternatively you can simply render it in the controller, since you've already composed the structure the following would be enough.或者,您可以简单地在控制器中渲染它,因为您已经组合了以下结构就足够了。
render json: @response
class MyController < ApplicationController
def getTracklist
begin
# you need to assign something to a variable
rescue StandardError => e
respond_to do |format|
format.any(:json, :js) do
render :json => {:error => e.message}
end
end
end
end
end
Making these changes to your controller can help you with your requirements.对您的控制器进行这些更改可以帮助您满足您的要求。 You don't need a view after doing this.
执行此操作后您不需要视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.