的iOS get请求到Rails与参数
问题描述:
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?
答
首先,您正在查找的动作是show
,而不是index
,如果您正在寻找RESTful服务。
要解决你提到你需要查询更改为错误:
@beers = Beer.where(:location_id => params[:location_id])
假设location_id
就是你要找的字段。
我会看看你的路线,它定义你的网址。他们不遵循正常的约定。
/locations/...
将属于Location
资源。
/beers/...
将属于Beer
资源。
你用目前的路线搞乱惯例(对你不利)。
感谢@Richard Brown,它确实解决了我在客户端上的错误,所以我将其标记为答案。我认为我需要仔细观察我的路线,所以我会提出另一个问题来解决这个问题。谢谢。 – jacobt 2013-03-09 18:57:59