我使用cancan gem为管理员方面做了动态许可的代码。
当我同意所有人并阅读/创建时。它会工作,但当我授予modle_name和read / create权限时。它会告诉我访问被拒绝。当存在权限时。
class ApplicationController < ActionController::Base
protect_from_forgery
rescue_from CanCan::AccessDenied do |exception|
logger.info("<.............#{exception.inspect}...........>")
flash[:alert] = "Access denied. You are not authorized to access the requested page."
redirect_to user_root_path
end
protected
#derive the model name from the controller. egs UsersController will return User
def self.permission
return name = self.name.gsub('Controller','').singularize.split('::').last.constantize.name rescue nil
end
def current_ability
@current_ability ||= Ability.new(current_user)
end
#load the permissions for the current user so that UI can be manipulated
def load_permissions
@current_permissions = current_user.roles.each do|role|
end
end
end
class Ability
include CanCan::Ability
def initialize(user)
user.roles.each do|role|
role.permissions.each do |permission|
if permission.subject_class == "all"
can permission.action.to_sym, permission.subject_class.to_sym
else
can permission.action.to_sym, permission.subject_class.constantize
end
end
end
end
end
当我同意这样的许可时:
permission.subject_class = PublicDoc
permission.action = create
会在控制台表单中显示错误
<....CanCan......:public_doc...........>
<....CanCan......:new...........>
<....CanCan......#<CanCan::AccessDenied: You are not authorized to access this page.>...........>
我做了一些像这样的代码。
请帮我解决这个问题。 谢谢。
答案 0 :(得分:1)
我编辑了我的Ability类:
class Ability
include CanCan::Ability
def initialize(user)
user.roles.each do|role|
role.permissions.each do |permission|
if permission.subject_class == "all"
can permission.action.to_sym, permission.subject_class.to_sym
else
can permission.action.to_sym, permission.subject_class.to_sym
end
end
end
end
end
并在下面的权限中传递值。
permission.subject_class = public_doc
permission.action = create
这对我有用。 :)