Rails 3 教程 10.4.2 : NoMethodError undefined 方法 'admin? for nil:nilClass



我正在构建自己的身份验证系统,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

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

在您

调用"destroy"方法时,您似乎没有当前用户,

我想是因为这条线

before_filter :admin_user,   :only => :destroy

如您所见,您仅在 :index,:show,:edit, :update 中设置current_user

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

溶液

将:d estroy添加到:authenticate方法应该可以解决问题,然后在您尝试销毁current_user时

before_filter :authenticate, :only => [:index,:show,:edit, :update, :destroy]
在这种情况下,

admin_user 方法中的current_user变量为 nil,因此您需要先检查对象是否为 nil:

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     

相关内容

  • 没有找到相关文章

最新更新