【问题标题】:Newbie: Ruby on rails. I am getting DoubleRenderError while using find_each新手:Ruby on rails。使用 find_each 时出现 DoubleRenderError
【发布时间】:2017-04-29 06:22:51
【问题描述】:

我有返回 JSON 数据的 API 方法。
示例

 http://myapp/items/get_list_of_Item_IDs_from_some_where.json?days=50&location=CA

正在工作的控制器中的方法:

def get_list_of_Item_IDs_from_some_where 
  item = Item.where("created_at >= ? and location = ?", Date.today - params[:days].to_i, params[:location])
    serialized_item_ids_and_updated_at = item.as_json(only: [:id, :updated_at])
    respond_to do |format|
      format.html
      format.json { render json: serialized_item_ids_and_updated_at }
    end
end

输出:

[{"id":"12345","updated_at":"2016-11-18T20:31:23Z"},{"id":"12222","updated_at":"2016-11-18T20:39:18Z"}]

当我厌倦了在该方法中使用 find_each 时,控制器中的方法不起作用。

def get_list_of_Item_IDs_from_some_where 
  Item.where("created_at >= ? and location = ?", Date.today - params[:days].to_i, params[:location]).find_each do |item|
    serialized_item_ids_and_updated_at = item.as_json(only: [:id, :updated_at])
    respond_to do |format|
      format.html
      format.json { render json: serialized_item_ids_and_updated_at }
    end
  end
end

输出:

我会收到这个错误:

AbstractController::DoubleRenderError 

【问题讨论】:

    标签: json ruby ruby-on-rails-3


    【解决方案1】:

    这对我有用。

    def get_list_of_Item_IDs_from_some_where 
      serialized_item_ids_and_updated_at = []
      Item.where("created_at >= ? and location = ?", Date.today - params[:days].to_i, params[:location]).find_each do |item|
      serialized_item_ids_and_updated_at << item.as_json(only: [:id, :updated_at])
      end
      respond_to do |format|
        format.html
        format.json { render json: serialized_item_ids_and_updated_at }
      end
    end
    

    【讨论】:

      【解决方案2】:

      每个请求只允许渲染一次,当您在块中使用渲染执行循环时,它将渲染与集合中的总项目一样多。

      这是我的解决方案:

      def get_list_of_Item_IDs_from_some_where 
        jsons = Item.where("created_at >= ? and location = ?", Date.today - params[:days].to_i, params[:location]).to_json(only: [:id, :updated_at])
        render json: jsons
      end
      

      【讨论】:

      • 我想在该方法中使用 find_each 批量处理对象。
      • 您想流式传输循环吗?你对 json 的期望是什么?
      • 这是我预期的 JSON [{"id":"12345","updated_at":"2016-11-18T20:31:23Z"},{"id":"12222","updated_at":"2016-11-18T20:39:18Z"}]
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多