CanCanCan会在异常上抛出常规Rails错误,而不是像我指定的那样闪烁消息

时间:2014-12-08 09:48:33

标签: ruby-on-rails-4 devise cancan rolify cancancan

我正在使用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

2 个答案:

答案 0 :(得分:2)

我在CanCan中不是很有经验,但我可以看到你正在从CanCan :: AccessDenied中抢救,而异常是一个NameError。因此,您不应期望您的救援块能够正常工作。

我会说你可能在某个地方拼错了'新闻室',或者在没有它的情况下访问它。

答案 1 :(得分:2)

事实证明,问题在于我授权我的Newsroom控制器的方式 - 因为Newsroom是一个非宁静的控制器(即没有与Newsroom相关联的模型。< / p>

我必须将它添加到我的控制器顶部:

authorize_resource :class => false

如此处所指定:https://github.com/CanCanCommunity/cancancan/wiki/Non-RESTful-Controllers#alternative-authorize_resource