i am doing and using for building my own authentication system, the Michael Hartls Tutorial for Rails 3 and came to an issue while doing it. I completed the whole section of 10.4.2 but when i got to the end and ran the test i always get this one error.
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/controll开发者_如何学编程ers/users_controller.rb:68:in `admin_user'
# ./spec/controllers/users_controller_spec.rb:245:in `block (5 levels) in <top (required)>'
I think it has something to do with my users controller in the admin area:
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
What is the problem and how do i fix this?
seems like you dont have a current user by the time you call 'destroy' method,
I think its because of this line
before_filter :admin_user, :only => :destroy
and as you can see, you are setting current_user only in :index,:show,:edit, :update
before_filter :authenticate, :only => [:index,:show,:edit, :update]
Solution
adding :destroy to :authenticate method should fix the issue, and then by the time you try to destroy the current_user is there
before_filter :authenticate, :only => [:index,:show,:edit, :update, :destroy]
Your current_user
variable in the admin_user
method is nil in that situation, so you need to check that the object isn't nil first:
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
精彩评论