0

我有这个http://localhost:3000/api/products请求,它返回带有产品对象列表的 json 格式输出。我听说在某些情况下最好使用 multi-gets 设计,您可以像这样在 URI 中列出产品 ID http://localhost:3000/api/products?ids=1,2,3,4。我的问题是如何配置路由以返回这样的 URI?下面是返回的json输出http://localhost:3000/api/products。提前谢谢

控制器

def index
@products=Product.all

respond_to do |format|
  format.json { render json: @products.to_json}
  format.xml
end
end

json输出
[

{
    "category_id": null,
    "created_at": "2011-03-25T13:35:16Z",
    "details": "Molestias pariatur consequuntur ut voluptas aperiam facere et et autem ad laudantium ut qui dolorem iste sit ut in dignissimos. Et debitis et et sunt quidem qui est est et numquam in dolorum natus sapiente nihil ipsa ratione. Quisquam aut molestiae earum voluptas vero et officiis magnam quam provident voluptatibus quia",
    "id": 1,
    "product_name": "Velit",
    "publisher_id": 1,
    "updated_at": "2012-11-12T18:45:13Z",
    "publisher_details": "http://localhost:3000/api/users/1"
},
{
    "category_id": null,
    "created_at": "2012-01-10T23:16:53Z",
    "details": "Temporibus quis et quam eveniet hic consequatur maiores eum expedita molestiae velit eligendi laboriosam ut molestiae. Velit delectus aliquid nobis quia velit aut dolorem omnis numquam reprehenderit quo illo saepe molestiae nisi. Soluta nihil quae soluta facilis cumque voluptates eaque amet unde non in placeat id cupiditate illum at et vero. Laborum id eaque voluptas illo eius iure",
    "id": 2,
    "product_name": "Nam Laboriosam Et Sed",
    "publisher_id": 1,
    "updated_at": "2012-11-12T18:45:13Z",
    "publisher_details": "http://localhost:3000/api/users/1"
}]
4

1 回答 1

4

有一个已停产的 gem,它是为 sproutcore(现为 ember)编写的,开箱即用:https ://github.com/drogus/bulk_api

但实际上,它根本不必那么难。对于单个控制器,我只会做类似的事情

 def index
   ids = params[:ids]
   if ids.blank?
     @categories = Category.all
   else  
     wanted_ids = ids.split(',')
     @categories = Categoriy.where(:id => wanted_ids)
   end
   render :json => @categories
 end

这有帮助吗?

于 2012-11-16T19:14:29.373 回答