'current_user' undefined in rails_admin with clearance
Asked Answered
C

1

7

I've been using rails_admin v0.7.0 with the clearance gem successfully up this point. I tried to update rails_admin to v1.0 today, but am getting an undefined variable or method error for current_user. In v0.7.0 it appears that RailsAdmin::MainController inherits from ApplicationController, whereas in v1.0 it inherits directly from ActionController::Base, which would explain current_user is now undefined (I believe current_user is defined in ApplicationController with the clearance gem). However, since I'm not finding anyone else with this problem, I'm thinking I must be missing something.

I wasn't the one who set up clearance on this app, but I don't think we're doing anything non-standard with it that would affect this. Clearance::Controller is included in ApplicationController. No special definition of current_user.

config/initializers/rails_admin.rb

RailsAdmin.config do |config|

  # Popular gems integration

  ## Clearance
  config.authorize_with do |controller|
    unless current_user.admin?
      redirect_to(
        main_app.root_path,
        alert: "You are not permitted to view this page"
      )
    end
  end

  config.current_user_method { current_user }
end
Cycloparaffin answered 11/10, 2016 at 6:0 Comment(0)
R
16

You are correct that Rails Admin inherits from ::ActionController::Base by default, and that is what is causing your issue. Fortunately, the fix is simple. Add config.parent_controller = "::ApplicationController" to config/initializers/rails_admin.rb:

RailsAdmin.config do |config|

  ## == Clearance ==
  config.parent_controller = "::ApplicationController"

  config.authorize_with do |controller|
    unless current_user && current_user.admin?
      redirect_to(
        main_app.root_path,
        alert: "You are not permitted to view this page"
      )
    end
  end

  # You actually don't need this line    
  # config.current_user_method { current_user }
end

I've created a reference repo here for comparison if you need it.

Runofthemill answered 1/11, 2016 at 13:56 Comment(1)
Thank you!! This line fixed it for me config.parent_controller = "::ApplicationController" I am using custom authDebus

© 2022 - 2024 — McMap. All rights reserved.