本文介绍了'current_user' 在 rails_admin 中未定义,但有许可的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我一直在使用 rails_admin v0.7.0 和清除宝石成功地.我今天尝试将 rails_admin 更新到 v1.0,但遇到 current_user 的未定义变量或方法错误.在 v0.7.0 中,RailsAdmin::MainController 似乎继承自 ApplicationController,而在 v1.0 中,它直接继承自 ActionController::Base,这将解释 current_user 现在未定义(我相信 current_user 是在 ApplicationController 中用清除宝石定义的).但是,由于我没有发现其他人有这个问题,我想我一定是遗漏了什么.

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.

我不是在此应用程序上设置许可的人,但我认为我们不会对其进行任何会影响此操作的非标准操作.Clearance::Controller 包含在 ApplicationController 中.current_user 没有特殊定义.

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

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

推荐答案

Rails Admin 默认从 ::ActionController::Base 继承是正确的,这就是导致您出现问题的原因.幸运的是,修复很简单.将 config.parent_controller = "::ApplicationController" 添加到 config/initializers/rails_admin.rb:

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

我已经创建了一个 参考 repo here 以供您在需要时进行比较.

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

这篇关于'current_user' 在 rails_admin 中未定义,但有许可的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 13:20