2013-03-09 54 views
0

API在我的Rails應用程序的iOS get請求到Rails與參數

位置have_many啤酒

啤酒belong_to位置

當iOS應用調用locations/%@/beers.json我要啤酒控制器與屬於啤酒迴應僅限於從iOS應用中調用的location_id。

這裏是從客戶端發送請求時,用戶點擊位置1.

Started GET "/locations/1/beers.json" for 127.0.0.1 at 2013-03-09 11:26:16 -0700 
Processing by BeersController#index as JSON 
    Parameters: {"location_id"=>"1"} 
    Beer Load (0.1ms) SELECT "beers".* FROM "beers" 
Completed 200 OK in 12ms (Views: 1.8ms | ActiveRecord: 0.4ms) 

這裏是我的啤酒控制器代碼

class BeersController < ApplicationController 

    def index 
    @beers = Beer.all 
    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render json: @beers } 
    end 
    end 

眼下,這將返回所有啤酒的列表給客戶,不管他們的location_id。

到目前爲止,我已經試過

class BeersController < ApplicationController 

    def index 
    @beers = Beer.find(params[:location_id]) 
    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render json: @beers } 
    end 
    end 

但是,崩潰的iOS應用,即使我得到一個狀態200

Started GET "/locations/1/beers.json" for 127.0.0.1 at 2013-03-09 11:19:35 -0700 
    Processing by BeersController#index as JSON 
     Parameters: {"location_id"=>"1"} 
     Beer Load (0.1ms) SELECT "beers".* FROM "beers" WHERE "beers"."id" = ? LIMIT 1 [["id", "1"]] 
    Completed 200 OK in 2ms (Views: 0.6ms | ActiveRecord: 0.1ms) 

在上面的請求應該不會是

Beer Load (0.1ms) SELECT "beers".* FROM "beers" WHERE "beers"."location_id" = ? LIMIT 1 [["location_id", "1"]]

如何更改我的控制器,使其響應啤酒只屬於客戶端發送的location_id?

回答

2

首先,您正在查找的動作是show,而不是index,如果您正在尋找RESTful服務。

要解決你提到你需要查詢更改爲錯誤:

@beers = Beer.where(:location_id => params[:location_id]) 

假設location_id就是你要找的字段。

我會看看你的路線,它定義你的網址。他們不遵循正常的約定。

/locations/...將屬於Location資源。

/beers/...將屬於Beer資源。

你用目前的路線搞亂慣例(對你不利)。

+0

感謝@Richard Brown,它確實解決了我在客戶端上的錯誤,所以我將其標記爲答案。我認爲我需要仔細觀察我的路線,所以我會提出另一個問題來解決這個問題。謝謝。 – jacobt 2013-03-09 18:57:59