我有返回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
答案 0 :(得分: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
答案 1 :(得分:0)
每个请求只允许渲染一次,当你在块中执行循环渲染时,它将渲染与集合中的总项目一样多的数量。
这是我的解决方案:
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