我在一个项目中使用CanCan来管理每个项目中每个实体的不同角色级别。我正在做这个:
# encoding: utf-8
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.is_admin == true
can :manage, :all
else
can :read, :all
Project.all.each do |project|
current_role_name = user.roles.find_by_project_id(project.id).role_name.name
if current_role_name.eql?'Auteur senior'
can :manage, [Project, Introduction, Abstract, Text, Conclusion, Asset, Attachment], :project_id => project.id
elsif current_role_name.eql?'Auteur junior'
can :manage, [Introduction, Abstract, Attachment], :project_id => project.id
can :update, Text, :project_id => project.id, :user_level => current_role_name
can :manage, [Asset], :project_id => project.id, :user_level => current_role_name
elsif current_role_name.eql?'Équipe phylogéniste'
can :manage, [Attachment], :project_id => project.id
can :manage, [Text, Asset], :project_id => project.id, :user_level => current_role_name
end
end
end
end
end当我检查用户role_name时,它可以工作,但当我想要使用这样的条件时:
can :update, Text, :project_id => project.id, :user_level => current_role_name条件不会有任何影响。我怎么才能让它工作呢?
发布于 2012-02-23 22:40:33
我终于找到了解决方案:
在相关的控制器中,我用load_and_authorize_resource替换了authorize_resource,仅此而已。
发布于 2012-02-23 00:39:54
我通常做的是:
1-在我的User类中定义角色,并将它们影响到用户。
class User
# CanCan roles ( see Users::Ability)
ROLES = %w[auteur_senior auteur_junior]
def roles=(roles)
self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
end
def roles
ROLES.reject do |r|
((roles_mask || 0) & 2**ROLES.index(r)).zero?
end
end
def is?(role)
roles.include?(role.to_s)
end
# define all bollean set/get methods for roles
ROLES.each do |r|
define_method "is_#{r}" do
self.roles += [r]
self
end
define_method "is_#{r}?" do
roles.include?(r)
self
end
end
end2-《我影响每个角色的能力》中的
class Ability
include CanCan::Ability
def initialize(user)
@user = user || User.new # for guest
@user.roles.each { |role| send(role) }
end
def auteur_junior
can :manage, [Introduction, Abstract, Attachment], :project_id => project.id
can :update, Text, :project_id => project.id, :user_level => current_role_name
can :manage, [Asset], :project_id => project.id, :user_level => current_role_name
end
def auteur_scenior
can :manage, [Project, Introduction, Abstract, Text, Conclusion, Asset, Attachment], :project_id => project.id
end
end发布于 2016-06-11 09:05:21
除非向authorize_resource方法传递实例,否则该方法将对该类调用authorize!。如果不使用load_resource或load_and_authorize_resource,则会将nil传递给authorize_resource before_filter。
Example from the CanCan documentation
#authorize_resource(*args) ⇒ Object
authorize!(params[:action].to_sym, @article || Article)如果你想用你自己的方法(而不是CanCan的load_resource)从数据库加载记录,并且有更多的控制,那么你可以创建你自己的方法,比如load_thing,然后用prepend_before_filter :load_thing调用它。这将在调用 authorize_resource 之前将记录加载到实例变量中,确保实例变量不为nil,并检查能力文件中指定的规则。
https://stackoverflow.com/questions/9393834
复制相似问题