2013-05-12 96 views
1

我试图创建后续/取消关注按钮,但我有错误在我的索引行动:为什么params [:id]是零?

没有ID找不到用户

users_controller.rb:

class UsersController < ApplicationController 
    before_filter :authenticate_user! 
    def index 
    @user = User.find(params[:id]) 
    end 
end 

我发现params[:id]nil。我对Rails很新,我不明白为什么它是nil

任何人都可以解释我做错了什么?

+0

你是否在你的请求中加入了'id'参数? – shem 2013-05-12 06:49:15

+0

您使用类型/用户/ put_id_here的网址 – av501 2013-05-12 06:49:33

回答

3

如果运行rake routes你会看到它的路线采取id,哪些没有,例如输出:

GET  /photos    index 
GET  /photos/new   new 
POST /photos create  create 
GET  /photos/:id   show 
GET  /photos/:id/edit edit 
PUT  /photos/:id   update 
DELETE /photos/:id   destroy 

所以在上面只showeditupdatedestroy路线可以采取id

除非你已经改变了你的路由,index通常用于收集,所以:

def index 
    @users = User.all # no id used here, retreiving all users instead 
end 

当然你也可以进行路由配置,请你,例如:

get "users/this-is-my-special-route/:id", to: "users#index" 

现在localhost:3000/users/this-is-my-special-route/12将调用用户index行动。虽然在这种情况下,您最好创建一个与之相对应的新路线和动作,而不是像这样改变索引。

您可以通过routing in Rails here了解更多信息。

+0

现在它是有道理的。非常感谢! – Blaze 2013-05-12 07:18:39