2013-05-12 102 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