我正在构建site-wide cancan身份验证系统。只是为了对我的尝试进行非常简单的验证,我每次尝试点击页面时都会初始化我的测试用例:
# application_controller.rb
class ApplicationController < ActionController::Base
admin = Role.new(name: :admin, is_default: true)
admin.permissions << Permission.create(action: :manage, subject_class: :all)
admin.save
current_user=User.create!
# users automatically get associations to all roles with `is_default: true`
check_authorization
end
只有skip_authorization_check
的控制器让我通过,其他所有人都会抛出AuthorizationNotPerformed
错误:
CanCan::AuthorizationNotPerformed in ExampleAuthEngin::PermissionsController#index
This action failed the check_authorization because it does not authorize_resource. Add skip_authorization_check to bypass this check.
我做错了什么?
答案 0 :(得分:3)
在控制器中,您需要致电load_and_authorize_resource
(在班级),或在个别行动中致电authorize! :action, resource
,其中:action
和resource
是进行测试。 load_and_authorize_resource将before_filters添加到控制器,该控制器实例化资源的实例变量(实例化方法基于操作,加载资源基于控制器名称),并添加过滤器以授权加载的资源,授权根据正在被击中的动作,执行:read,:create,:update或:destroy。
您可以详细了解here。