'current_user' undefined in rails_admin with clearance

泪湿孤枕 提交于 2021-02-07 14:22:17

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/39971235/current-user-undefined-in-rails-admin-with-clearance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!