2011-05-07 69 views
2

我在做和使用建立我自己的身份驗證系統,the Michael Hartls Tutorial for Rails 3,並在做到這一點時遇到了問題。我完成了10.4.2的全部內容,但是當我到最後並且進行測試時,我總是得到這個錯誤。Rails 3教程10.4.2:NoMethodError未定義方法`admin?'爲零:NilClass

1) UsersController GET 'index' DELETE 'destroy' as a non-signed-in user should deny access 
    Failure/Error: delete :destroy, :id => @user 
    NoMethodError: 
     undefined method `admin?' for nil:NilClass 
    # ./app/controllers/users_controller.rb:68:in `admin_user' 
    # ./spec/controllers/users_controller_spec.rb:245:in `block (5 levels) in <top (required)>' 

我認爲這是與我的用戶控制器在管理方面:

class UsersController < ApplicationController 
    before_filter :authenticate, :only => [:index,:show,:edit, :update] 
    before_filter :correct_user, :only => [:edit, :update] 
    before_filter :admin_user, :only => :destroy 
     . 
     . 
     . 
     . 
     . 
    def destroy 
     User.find(params[:id]).destroy 
     flash[:success] = "USER DELETED." 
     redirect_to users_path 
    end 


    private 

     def authenticate 
      deny_access unless signed_in? 
     end 

     def correct_user 
      @user = User.find(params[:id]) 
      redirect_to(root_path) unless current_user?(@user) 
     end 

     def admin_user 
      redirect_to(root_path) unless current_user.admin? 
     end     
end 

這是什麼問題?如何解決這一問題?

回答

6

好像你沒有的時候當前用戶你稱之爲「破壞」的方法,

我想是因爲這條線

before_filter :admin_user, :only => :destroy 

它,正如你所看到的,你ONL設定CURRENT_USER Ÿ在:指數:顯示,編輯,:更新

before_filter :authenticate, :only => [:index,:show,:edit, :update] 

解決方案

增加:摧毀到:身份驗證方法應該可以解決問題,那麼到時候你試圖摧毀CURRENT_USER有沒有

before_filter :authenticate, :only => [:index,:show,:edit, :update, :destroy] 
2

你在admin_user方法current_user變量是在這種情況下爲零,所以你需要檢查的對象不是零第一:

def admin_user 
    authenticate # if this method doesn't terminate the processing, you'll have to alter the line below too 
    redirect_to(root_path) unless current_user.admin? 
    # or: redirect_to(root_path) unless current_user && current_user.admin? 
end  
+0

好的,是這個代碼檢查該對象?如果仍然沒有運氣。 – LearningRoR 2011-05-07 05:32:40

相關問題