Cancan +设计rescue_from没有捕获exception

我正在实现Devise和Cancan用于用户身份validation和权限。 到目前为止,一切都很好,但我不能在不允许用户访问特定function时将用户重定向到登录页面。

我的测试是:

feature 'A signed in user' do before(:each) do user = FactoryGirl.create(:user) visit "/login" fill_in "user_email", :with => user.email fill_in "user_password", :with => "ilovebananas" click_button "Sign in" end scenario 'should not have access to admin dashboard' do visit '/admin' page.should have_content 'Log in' end end 

我得到以下失败:

 Failures: 1) A signed in user should not have access to admin dashboard Failure/Error: visit '/admin' CanCan::AccessDenied: You are not authorized to access this page. 

要清楚,除了重定向到登录页面之外,我的所有权限管理到目前为止都按预期工作。


以下是设置方式:

ApplicationController中:

 check_authorization :unless => :devise_controller? # Cancan rescue_from CanCan::AccessDenied do |exception| redirect_to login_path, alert: exception.message end 

UsersController

 class UsersController < ApplicationController load_and_authorize_resource # Cancan def queue ... end ... end 

AdminsController

 class AdminController  false # Cancan, used because AdminController doesn't have an associated model ... end 

ability.rb

 class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user, not logged in can :queue, User if user.has_permission? :super_admin can :manage, :all elsif user.has_permission? :network_admin end end end 

我错过了什么?

你必须将类名作为字符串传递。 试着引用它。 或尝试

 rescue_from CanCan::AccessDenied , :with => :login_page private def login_page redirect_to login_path end 

您应该无条件地将“controller.authorize_resource”添加到admin / register.if能力。

 controller.authorize_resource 

示例:can:manage,:all

如果条件是,

 controller do load_and_authorize_resource :except => [:update,:index, :show, :edit] def scoped_collection end_of_association_chain.accessible_by(current_ability) end end 

示例:can:manage,Master :: Country,:organization_branch_id => each_branch.id

我希望它对你有所帮助

我的Admins Controller不是

做出改变解决了我的问题。