具有cans的rails_admin无法捕获重定向的拒绝访问异常 [英] rails_admin with cancan not catching access denied exception for redirect

查看:87
本文介绍了具有cans的rails_admin无法捕获重定向的拒绝访问异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用rails 5,rails_admin,devise和cancancan。

I am using rails 5, rails_admin, devise and cancancan.

一切正常,但是当访问被拒绝时,它会显示您无权访问此页面的错误屏幕。

Everything works correctly, but when there is access denied, it shows a 'You are not authorized to access this page' error screen.

我想重定向到root_path,我一直在搜索,但我只发现我必须在app / controllers / application_controller中写东西。 rb这段代码:

I want to redirect to root_path, I've been searching and I only found that I have to write in app/controllers/application_controller.rb this code:

class ApplicationController < ActionController::Base    
    rescue_from CanCan::AccessDenied do |exception|
        redirect_to root_path, :alert => exception.message
    end
end

我做到了,但我仍然错误消息中的内容(未经授权)。它不会重定向。

And I did, but I am still in the error message when not authorised. It does not redirect.

我认为其余代码必须可以,因为它可以工作,但不能重定向到任何地方。

I think the rest of the code must be ok, because it works, but not redirecting to anywhere.

#config/initializers/rails_admin.rb
config.authorize_with :cancan
config.current_user_method(&:current_user)

#app/models/ability.rb
class Ability
    include CanCan::Ability

    def initialize(user)

    user ||= User.new # guest user (not logged in)
    if user.admin
        can :access, :rails_admin       # only allow admin users to access Rails Admin
        can :dashboard           
        can :manage, :all
    else
        can :read, :all                   # allow everyone to read everything
    end
  end
end

我看到更多人在问同样的问题,但是所有人都没有答案。我找到了3个答案,但是我不明白被接受的解决方案,因为它实际上没有解释任何解决方案:
可以+从不捕获异常的情况中拯救出一个资源

I saw more people asking the same, but all of them are without answers. I found one with 3 answers, but I don't understand the accepted solution because it really do not explain any solution: Cancan + Devise rescue_from not catching exception

推荐答案

默认情况下,看起来 ApplicationController 实际上不是 RailsAdmin :: MainController 的父级。因此,当 RailsAdmin :: MainController 抛出 CanCan :: AccessDenied 异常时,它实际上从未触及 ApplicationController ,救援块就不会启动。

It looks like ApplicationController isn't actually a parent of RailsAdmin::MainController by default. So, when RailsAdmin::MainController throws the CanCan::AccessDenied exception, it never actually touches ApplicationController, and the rescue block never kicks in.

您可以显式声明 ApplicationController 作为 rails_admin.rb 配置块中

You can explicitly declare ApplicationController as the parent for RailsAdmin::MainController in the rails_admin.rb config block with

config.parent_controller = 'ApplicationController' 

这篇关于具有cans的rails_admin无法捕获重定向的拒绝访问异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆