Ruby on rails 为什么params[:id]为零?

Ruby on rails 为什么params[:id]为零?,ruby-on-rails,twitter-follow,Ruby On Rails,Twitter Follow,我试图创建“跟随/取消跟随”按钮,但在索引操作中出现错误: 找不到没有ID的用户 用户\u controller.rb: class UsersController < ApplicationController before_filter :authenticate_user! def index @user = User.find(params[:id]) end end class UsersController

我试图创建“跟随/取消跟随”按钮,但在索引操作中出现错误:

找不到没有ID的用户

用户\u controller.rb:

class UsersController < ApplicationController
  before_filter :authenticate_user!
  def index
    @user = User.find(params[:id])
  end
end
class UsersController
我发现
params[:id]
nil
。我对Rails非常陌生,我不明白为什么它是
nil


有人能解释一下我做错了什么吗?

如果运行
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
因此,在上述情况下,只有
显示
编辑
更新
销毁
路由可以使用
id

除非您更改了路线,
索引通常用于集合,因此:

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/这是我的特殊路线/12
将调用用户
index
操作。虽然在这种情况下,您最好创建一个与之对应的新路由和操作,而不是像那样更改索引


您可以阅读更多信息。

您是否在请求中添加了'id'参数?您是否在此处使用了/users/put_id_类型的url?现在有意义了。谢谢!