0

I want to change my layout based on whether or not the current user is an admin. So I made a simple method to check if current user is admin, I then call that method in application controller. I keep getting the following error:

undefined method `is_admin?' for ApplicationController:Class

My code looks like this:

class ApplicationController < ActionController::Base
  protect_from_forgery

  helper_method :current_user, :is_admin?


  if is_admin?
   layout 'admin'
  end

  .....

  protected

  .....

  def is_admin?
    if current_user.user_role == 'admin'
      return true
    end
  end

end

How should I be doing this?

Thanks

1 Answer 1

1

The way you have it currently, is_admin? is being run when the class is loaded, and it's executed in the class scope (hence the exception, since it is not a class method). You need to check for the admin status in an instance method, during the request process.

To do what you're trying to do you could have the layout call an instance method, e.g.

layout :determine_layout

protected

# return "admin" for the layout if `is_admin?`, otherwise "application"
def determine_layout
  is_admin? ? 'admin' : 'application'
end

Edit: Some possibly helpful links:

Sign up to request clarification or add additional context in comments.

1 Comment

Great help! Where can I read more on how files are loaded and what scope to expect for different files? if that makes sense...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.