【问题标题】:Ruby API response view : how can I render a JSON response?Ruby API 响应视图:如何呈现 JSON 响应?
【发布时间】: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


    【解决方案1】:

    有多种方法可以实现您想要的。您可以merge! 将响应放入 jbuilder 根目录中。

    json.merge! @response
    

    以上将所有键/值对合并到 jbuilder 根目录中。您也可以选择extract! 特定属性。

    json.extract! @response, :error
    

    或者,您可以简单地在控制器中渲染它,因为您已经组成了以下结构。

    render json: @response
    

    【讨论】:

    • 即使其他人是对的,也是最完整的回应。谢谢,没有视图 = 更好!
    【解决方案2】:

    您可以为 jBuilder 执行此操作:

    json.merge!(@response)
    

    Source

    【讨论】:

      【解决方案3】:
      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
      

      对控制器进行这些更改可以帮助您满足您的要求。 完成此操作后您不需要视图。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-02
        • 2012-10-09
        • 1970-01-01
        • 2011-04-07
        • 2012-10-09
        • 1970-01-01
        • 2014-09-06
        • 2021-05-11
        相关资源
        最近更新 更多