2016-01-09 48 views
1

我做了使用cancan gem的管理員端的動態權限代碼。動態權限不能用於cancan中的單個模型

當我給所有權限,並閱讀/創建。它會工作,但是當我給modle_name許可和讀/創建。它會告訴我訪問被拒絕。當權限是存在的。

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.>...........> 

我做了一些這樣的代碼。

http://blog.joshsoftware.com/2012/10/23/dynamic-roles-and-permissions-using-cancan/?blogsub=confirming#subscribe-blog

請幫我解決這個問題。 謝謝。

回答

1

我編輯我的能力類這樣的:

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 

這是爲我工作。 :)