获取代表用户的CanCan功能的字符串 [英] Get a string that represents a user's CanCan abilities
问题描述
我想缓存Post
视图,但是该视图取决于当前用户的权限(例如,如果current_user.can?(:edit, @post)
,我仅显示"edit"链接)
I want to cache a Post
view, but the view depends on the permissions of the current user (e.g., I only show the "edit" link if current_user.can?(:edit, @post)
)
因此,我希望我的缓存键包括当前用户的CanCan能力的表示形式,以便我可以在用户能力发生变化时使缓存无效
So I'd like my cache key to include a representation of the current user's CanCan abilities, so that I can invalidate the cache when the user's abilities change
SO:我如何获得一个表示当前用户能力的字符串,以便2个具有相同能力的不同用户将生成相同的能力字符串"?
SO: how can I get a string that represents the current user's abilities such that 2 different users with the same abilities will generate the same "ability string"?
我已经尝试过user.ability.inspect
,但这不会为具有相同功能的不同用户生成相同的字符串
I've tried user.ability.inspect
, but this doesn't produce the same string for different users who have the same abilities
推荐答案
针对CanCanCan进行了修订
从CanCanCan版本1.12(CanCan的社区延续)开始,Ability.new(user).permissions
返回具有给定用户所有权限的哈希.
As of version 1.12 of CanCanCan (the community continuation of CanCan), Ability.new(user).permissions
returns a hash with all permissions for the given user.
上一个答案(CanCan):
这可能有点复杂...但是在这里.
This might be a little complex...but here it goes..
如果将指定的用户传递到CanCan所需的Ability模型中,则可以使用instance_variable_get访问该用户角色的定义,然后将其分解为所需的任何字符串值.
If you pass the specified User into the Ability model required by CanCan, you can access the definition of that users role using instance_variable_get, and then break it down into whatever string values you want from there..
>> u=User.new(:role=>"admin")
>> a=Ability.new(u)
>> a.instance_variable_get("@rules").collect{
|rule| rule.instance_variable_get("@actions").to_s
}
=> ["read", "manage", "update"]
如果您想知道这些规则所基于的模型,可以访问@subjects实例变量以获取其名称.
if you want to know the models in which those rules are inflicted upon, you can access the @subjects instance variable to get its name..
这是我与(pp)一起工作的Ability的模型布局
here is the model layout for Ability from which I worked with (pp)
Ability:0x5b41dba @rules=[
#<CanCan::Rule:0xc114739
@actions=[:read],
@base_behavior=true,
@conditions={},
@match_all=false,
@block=nil,
@subjects=[
User(role: string)]>,
#<CanCan::Rule:0x7ec40b92
@actions=[:manage],
@base_behavior=true,
@conditions={},
@match_all=false,
@block=nil,
@subjects=[
Encounter(id: integer)]>,
#<CanCan::Rule:0x55bf110c
@actions=[:update],
@base_behavior=true,
@conditions={:id=>4},
@match_all=false,
@block=nil,
@subjects=[
User(role: string)]>
]
这篇关于获取代表用户的CanCan功能的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!