Vijay Jadon
Vijay Jadon

Reputation: 77

Undefined method `admin?' for nil:NilClass

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

Answers (5)

Adnan Devops
Adnan Devops

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

Prashant4224
Prashant4224

Reputation: 1601

This may help you

 def require_admin
   redirect_to '/' if current_user && current_user.admin?
 end

Upvotes: 0

Akshay Borade
Akshay Borade

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

Marek Lipka
Marek Lipka

Reputation: 51151

You get this error because you're not signed in, so your current_user method returns nil.

Upvotes: 1

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

current_user.try(:admin?)

This will check if current user is present

Upvotes: 3

Related Questions