动态权限不适用于 cancan 中的单个模型

Dynamic Permission is not working for single model in cancan

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

is 将以控制台形式向我显示错误

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

请帮我解决这个问题。 谢谢。

我将我的能力 class 编辑为:

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

这对我有用。 :)