我想缓存Post
View ,但是该 View 取决于当前用户的权限(例如,如果current_user.can?(:edit, @post)
,我仅显示“edit”链接)
因此,我希望我的缓存键包括当前用户的CanCan功能的表示形式,以便我可以在用户功能更改时使缓存无效
SO:如何获得表示当前用户能力的字符串,以便具有相同能力的2个不同用户将生成相同的“能力字符串”?
我已经尝试过user.ability.inspect
,但是对于功能相同的不同用户,它不会产生相同的字符串
最佳答案
编辑:修改为CanCanCan
从CanCanCan 1.12版(CanCan的社区延续)开始,Ability.new(user).permissions
返回具有给定用户所有权限的哈希。
上一个答案(CanCan):
这可能有点复杂...但是在这里。
如果将指定的用户传递到CanCan所需的能力模型中,则可以使用instance_variable_get访问该用户角色的定义,然后将其分解为所需的任何字符串值。
>> 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实例变量以获取其名称。
这是我与之合作的能力的模型布局(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)]>
]
关于caching - 获取代表用户的CanCan功能的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9809203/