[英]Rails Tutorial: NoMethodError: undefined method `each' for nil:NilClass
[英]Rails 3 Tutorial 10.4.2 : NoMethodError undefined method `admin?' for nil:NilClass
我正在做和使用建立我自己的身份驗證系統, 邁克爾哈特爾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
如您所見,您只在以下位置設置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]
在這種情況下, 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.