CanCanCan在异常情况下会抛出一个普通的Rails错误,而不是像我指定的那样显示一个flash消息。

12

我正在使用 CanCanCan、Devise 和 Rolify。

我的 ApplicationController 看起来像这样:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_filter :new_post

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

  def new_post
    @post = Post.new
  end  

end

我的routes.rb文件看起来像这样:

  authenticate :user, lambda { |u| u.has_role? :admin or :editor } do
    get 'newsroom', to: 'newsroom#index', as: "newsroom"
    get 'newsroom/published', to: 'newsroom#published'
    get 'newsroom/unpublished', to: 'newsroom#unpublished'    
  end

# truncated for brevity
  root to: "posts#index"

这是与之相关的ability.rb文件:

elsif user.has_role? :member
    can :read, :all
    cannot :read, :newsroom

因此,当我以: member身份登录,并尝试访问/newsroom时,我会收到以下错误:

NameError at /newsroom
uninitialized constant Newsroom

与我预期的不同,没有被重定向到root_url并伴随一个:alert

不确定这里发生了什么。

编辑1

值得一提的是,只有当我把这段代码添加到我的NewsroomController中时,才会出现这个问题:

authorize_resource

1
如果您作为管理员访问/newsroom,会触发错误吗? - Typpex
@Typpex 如果我以管理员身份登录并访问/newsroom,它会引发错误。 - marcamillion
2个回答

2

2

我对CanCan不是很有经验,但我可以看到你正在从CanCan :: AccessDenied中进行救援,而异常是一个NameError。因此,您不应该指望您的救援块起作用。

我想说,您可能在某个地方拼错了“Newsroom”,或者在它不可用的位置访问了它。


文档说在异常处理中,我们应该从 CanCan::AccessDenied 进行 rescue - https://github.com/CanCanCommunity/cancancan/wiki/Exception-Handling - marcamillion

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接