Reputation: 77
I have restricted one page from other users but if I am not logged in and visit that page, I get an error in the line redirect_to '/' unless current_user.admin?
but if I am logged in and visit the page,it works fine.
In my Application
controller
class ApplicationController < ActionController::Base
def require_admin
redirect_to '/' unless current_user.admin?
end
PLEASE can anyone tell me why is this error coming Thanks in advance!!!
Upvotes: 0
Views: 596
Reputation: 503
Check if you are logged in your application and do the following:
def require_admin
redirect_to root_path if current_user && current_user.admin?
end
Instead of writing redirect_to '/', you can use root_path to redirect to your home page.
Upvotes: 2
Reputation: 1601
This may help you
def require_admin
redirect_to '/' if current_user && current_user.admin?
end
Upvotes: 0
Reputation: 2472
Ensure that current_user is always a user instance, or check that it's not nil:
if current_user && current_user.admin?
You could alternatively use current_user.try(:admin?)
and it will fail silently if current_user is nil.
Upvotes: 0
Reputation: 51151
You get this error because you're not signed in, so your current_user
method returns nil
.
Upvotes: 1
Reputation: 3803
current_user.try(:admin?)
This will check if current user is present
Upvotes: 3