Ruby on rails Ruby API响应视图:如何呈现JSON响应?
我是Ruby新手,正在尝试构建API 我遵循了一个教程,能够在调用API端点时返回JSON响应 在本例中,调用的函数会引发一个错误,我希望将其作为JSON响应传递 my_controller.rb 事情是, 这是可行的,但我的回答是Ruby on rails Ruby API响应视图:如何呈现JSON响应?,ruby-on-rails,json,ruby,api,Ruby On Rails,Json,Ruby,Api,我是Ruby新手,正在尝试构建API 我遵循了一个教程,能够在调用API端点时返回JSON响应 在本例中,调用的函数会引发一个错误,我希望将其作为JSON响应传递 my_controller.rb 事情是, 这是可行的,但我的回答是 {"response":{"error":"the error message"}} 而我想把它当作 {"error":"the error message"} 我尝试将我的观点改为 json @response 但它失败了: ActionView::Temp
{"response":{"error":"the error message"}}
而我想把它当作
{"error":"the error message"}
我尝试将我的观点改为
json @response
但它失败了:
ActionView::Template::错误未定义的方法“json”
你是说?JSON:
1:json@response
那么,我如何能够在不将其放入属性的情况下完整地呈现我的响应呢
我在阅读有关ROR的资料时也看到,有时会使用此代码,我想知道在这种情况下如何使用它:
render json: { error_code:'not_found', error: e.message }, status: :not_found
谢谢 您可以为jBuilder执行以下操作:
json.merge!(@response)
对控制器进行这些更改可以帮助您满足需求。
完成此操作后,您不需要视图。有多种方法可以实现您的目标。您可以将响应输入到jbuilder根目录中
json.merge! @response
上面的代码将所有键/值对合并到jbuilder根目录中。您还可以选择特定属性
json.extract! @response, :error
或者,您可以简单地在控制器中渲染它,因为您已经编写了结构,下面就足够了
render json: @response
即使其他人是对的,也是最完整的回答。谢谢,无视图=更好!
json.merge! @response
json.extract! @response, :error
render json: @response