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

时间:2011-05-07 04:22:49

标签: ruby-on-rails ruby ruby-on-rails-3

我正在做并使用构建我自己的身份验证系统the Michael Hartls Tutorial for 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)>'

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

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

问题是什么?如何解决这个问题?

2 个答案:

答案 0 :(得分:6)

在您调用'destroy'方法

时,您似乎没有当前用户

我认为这是因为这一行

before_filter :admin_user,   :only => :destroy

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

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

<强>解决方案

添加:destroy to:authenticate方法应该修复问题,然后当你试图销毁current_user时就有了

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

答案 1 :(得分:2)

current_user方法中的admin_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