2016-05-16 110 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 
相關問題