Abram
Abram

Reputation: 41874

Devise current_user = nil in ApplicationController

Here is the full error:

Can't verify CSRF token authenticity
  User Load (0.3ms)  SELECT  `users`.* FROM `users`  WHERE `users`.`id` = 5  ORDER BY `users`.`id` ASC LIMIT 1
   (0.1ms)  BEGIN
   (0.2ms)  COMMIT
Completed 500 Internal Server Error in 22ms

NoMethodError - undefined method `has_role?' for nil:NilClass:
  app/controllers/application_controller.rb:8:in `authenticate_admin_user!'

I can verify that I was logged in at the time with an admin user.

Here is the controller that is triggering the error:

class ApplicationController < ActionController::Base
  def authenticate_admin_user!
    unless current_user.has_role? :admin
      flash[:alert] = "This area is restricted to administrators only."
      redirect_to main_app.root_path 
    end
  end

Upvotes: 1

Views: 1548

Answers (2)

Alaa Othman
Alaa Othman

Reputation: 1149

Add this line in your application controller so that the current_user method will be defined

before_action :authenticate_user!

Upvotes: 1

knrz
knrz

Reputation: 1811

Change
unless current_user.has_role? :admin

To this:
unless current_user.try(:has_role?, :admin)

What that does it it'll try calling the :has_role? method (with the :admin parameter, but instead of raising an exception it'll return nil.

Upvotes: 0

Related Questions