Rails 3教程10.4.2:NoMethodError未定义方法`admin?' 为零:NilClass

Lea*_*RoR 2 ruby ruby-on-rails ruby-on-rails-3

我正在做和使用建立我自己的身份验证系统,迈克尔哈特尔Rails 3教程,并在这样做时遇到了一个问题.我完成了10.4.2的整个部分,但是当我到达最后并运行测试时,我总是得到这一个错误.

 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)>'
Run Code Online (Sandbox Code Playgroud)

我认为它与管理区域中的用户控制器有关:

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
Run Code Online (Sandbox Code Playgroud)

有什么问题,我该如何解决这个问题?

sam*_*207 6

看起来你在调用'destroy'方法时没有当前用户,

我认为这是因为这条线

before_filter :admin_user,   :only => :destroy
Run Code Online (Sandbox Code Playgroud)

如您所见,您只在以下位置设置current_user:index,:show,:edit,:update

before_filter :authenticate, :only => [:index,:show,:edit, :update]
Run Code Online (Sandbox Code Playgroud)

添加:destroy to:authenticate方法应该修复问题,然后当你尝试销毁current_user时就在那里

before_filter :authenticate, :only => [:index,:show,:edit, :update, :destroy]
Run Code Online (Sandbox Code Playgroud)