2016-05-16 75 views
0

我环顾四周,但似乎无法找到任何类似的查询通过API(这是iOS应用程序的后端)基本上,我想要能够做的是作出这样的路线:在rails中查询多条记录API

localhost:3000/api/products/52,53,67,78,etc... 

而且这个查询将与IDS 52,53,67,78和以往其他ID列退回产品。目前,我有像一个普通的路线:

localhost:3000/api/products/52 

这正确检索该产品具有52的API我目前的路线是这样的:

namespace :api, defaults: {format: :json} do 
scope module: :v1 do 
    resources :products, only: [:index, :show, :destroy, :create] do 
    resources :reviews, only: [:index] 
    end 
    get '/search/products', to: "products#search" 
    resources :categories, only: [:index, :show] 
    resources :charges, only: [:create] 
    resources :customers, only: [:create] 
    resources :users, only: [:create, :show] 
    resources :accounts, only: [:create] 
    post '/login', to: "sessions#create" 

end 
end 

感谢您的帮助。

回答

2

为什么不直接发送ids作为params数组?

HTTP查询使用参数(或把它作为x-www-form-urlencoded recommened):

localhost:3000/api/products?ids[]=52&ids[]=53&ids[]=67... 

而且在exmple行动:

def index 
    products = Product.where('id IN (?)', params[:ids]) 
    if products.any? 
     render json: { success: true, products: products } 
    else 
     render json: { success: false, products: products } 
    end 
    end 
+0

我所有的编码请求作为JSON,而宁愿不惹我已经设置了在iOS应用解决路由器它只为某些请求创建异常,并使用JSON我无法在GET请求中发送参数 – joey

+0

将它作为'x-www-form-urlencoded'发送 –

2

正如其他人的建议,你应该通过PARAMS为阵列:

http://localhost:3000/api/products?ids[]=52&ids[]=53&ids[]=67

豪版本,控制器代码可能会比别人的答案有什么建议甚至更短:

def index 
    products = Product.where(id: params[:ids]) 
    render json: { success: products.any?, products: products } 
end 
相关问题