cancan 每个用户一个角色:通过一系列条件语句累积定义角色?
我正在使用 cancan,每个用户一个角色。角色是整数而不是字符串。我的ability.rb 是这样组织的:
def initialize(user, session)
if user.role.to_i == 9
can :create, [Resource1, Resource2, Resource3]
can :update, [Resource1, Resource2, Resource3]
elsif user.role.to_i == 8
can :create, [Resource1, Resource2]
can :update, [Resource1, Resource2]
else
can :create, Resource1
can :update, Resource1
end
end
实际上有 7 个角色而不是 3 个,而且文件要复杂得多。是否可以像这样重写文件,以便可以通过条件语句累积定义角色?
def initialize(user, session)
if user.role.to_i >= 9
can :create, Resource3
can :update, Resource3
end
if user.role.to_i >= 8
can :create, Resource2
can :update, Resource2
end
can :create, Resource1
can :update, Resource1
end
我想知道在重写整个文件之前,带有条件语句的精确结构是否有效。谢谢。
I am using cancan with one role per user. The roles are integers instead of strings. My ability.rb is organized like this:
def initialize(user, session)
if user.role.to_i == 9
can :create, [Resource1, Resource2, Resource3]
can :update, [Resource1, Resource2, Resource3]
elsif user.role.to_i == 8
can :create, [Resource1, Resource2]
can :update, [Resource1, Resource2]
else
can :create, Resource1
can :update, Resource1
end
end
In reality there are 7 roles instead of 3 and the file is much more complex. Could the file be rewritten like this instead so a role can be defined cumulatively through the conditional statements?
def initialize(user, session)
if user.role.to_i >= 9
can :create, Resource3
can :update, Resource3
end
if user.role.to_i >= 8
can :create, Resource2
can :update, Resource2
end
can :create, Resource1
can :update, Resource1
end
I'd like to know if this EXACT structure with the conditional statements would work before i rewrite the entire file. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的(除了比较)。看这里,它添加了规则。
编辑:以防万一它可能有用。
编辑2:
第一部分是什么意思?
首先,很抱歉粘贴了错误的代码块。然后,您可以看到您正在添加一条新规则,其主题是您传递给
can
的规则。在规则
初始化程序,你可以看到这一行:这意味着如果你有一个数组,你仍然拥有该数组(这就是
展平
的用途),但如果你只有一个资源,你会得到一个单项数组。您可以在代码中进行更多挖掘,您会注意到具有一种资源的规则的行为与仅具有一种资源的规则不同。然后将此规则添加到
rules
中,而不替换任何其他规则。现在希望已经很明确了。
Yes (except for the comparison). Look here, it adds the rule.
Edit: In case it may be useful.
Edit 2:
What does the first part mean?
In first place, sorry for pasting the wrong chunk of code. Then, you can see you are adding a new rule whose subject is the one you passed to
can
. InRule
initializer, you can see the line:that means that if you had an array you still have that array (that's what
flatten
is for), but if you had only one resource you get a one-item array. You can dig more in the code and you will notice than a rule with one resource behaves as a rule with only one.Then this rule is added to
rules
without replacing any other.Hope is clear now.