首页 文章

Rails:CanCanCan - 无法显示AccessDenied错误

提问于
浏览
0

我在我的rails应用程序中使用CanCanCan进行授权 . 路由和重定向工作正常但我没有设法显示AccessDenied错误消息(它之前工作但我必须在途中弄乱了一些东西,现在它不会显示) .

这是我的代码:

controllers/application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_url, error: exception.message
  end
  ...
end

(我将默认的 :alert 更改为 :error ,否则我最终会收到来自设计的警报('You are already logged in') .

views/index.html.haml (根)

= flash[:error] if flash[:error]
...

关于如何让它再次运作的任何想法?提前致谢 .

---EDIT---

我尝试了一些修复(没有成功):

  • messagenotice 替换 error

  • 完全删除 rescue_from CanCan::AccessDenied 方法 - 它将我带到标准的CanCan错误页面(所以我知道方法本身正在运行) .

  • 用常规字符串替换 exception.message .

  • 在重定向之前添加一个puts语句 - 它会像预期的那样在控制台中打印出来 .

  • 正如@Anand Shah在回答这个问题时建议的那样question,我在观点中补充了以下内容:

  • 如果flash [:error] .blank? %p flash hash为空

哈希确实是空的,所以看起来闪存根本就没有被保存 . 然后我补充说

flash.keep(:错误)

在我的控制器,但没有改变任何东西 .

3 回答

  • 0

    您是否通过私人浏览器尝试过,以防cookie搞砸了?

    你能试试这种格式吗?

    redirect_to(root_url, {:flash => { :error => exception.message }})
    
  • 0

    您是否尝试过不处理此内联,而是类似于:

    rescue_from CanCan::AccessDenied do |exception|
        flash[:error] =  exception.message
        redirect_to root_url
     end
    

    它之前工作的原因是Rails在 redirect_to 期间将 :alert:notice 理解为闪存消息,否则你应该使用“通用 flash 桶”,因为他们通过 flash: {error: 'your message'} 调用它

    但是传递给 redirect_toHash 也可以包含http状态代码( :status )和url查询参数(任何不是 :alert:notice:status:flash 的东西,它们只是看起来像是太多噪音(IMO)来放置一条flash消息在那里保存1行显式代码 .

  • 0

    这个问题的原因结果是我的 routes.rb . 除了为设计范围定义根之外:

    devise_scope :user do
      root to: "devise/sessions#new"
    end
    
    authenticated :user do
      root 'application#show', as: :authenticated_root
    end
    

    我还有一个额外的根定义(基本上导致双重定向,因此丢失警报):

    root to: 'application#show'
    

    在必要的修改之后,文档中的代码工作得很好(注意我可以将它从 error 带回 alert 而不会破坏事物):

    rescue_from CanCan::AccessDenied do |exception|
      redirect_to root_url, alert: exception.message
    end
    

相关问题