cancan,每个用户一个角色 - 有什么方法可以在不重复这么多文本的情况下设置能力?
我的能力模型看起来像这样:
class Ability
include CanCan::Ability
def initialize(user)
if user.role == "moderator"
can :manage, [Forum, Post]
elsif user.role == "admin"
can :manage, [Enrollment, SiteCare, Forum, Post]
elsif user.role == "superadmin"
can :manage, [Permission, Enrollment, SiteCare, Forum, Post]
end
end
end
实际上,一些角色管理着十几个项目。为了简化事情,我如何构建一些 ruby 来使我不必复制这么多文本?也许像这样的构造?
class Ability
include CanCan::Ability
def initialize(user)
a = "Forum, Post"
b = "Enrollment, SiteCare"
c = "Permission"
if user.role == "moderator"
can :manage, [{a}]
elsif user.role == "admin"
can :manage, [{a + b}]
elsif user.role == "superadmin"
can :manage, [{a + b + c}]
end
end
end
谢谢。
PS我知道每个用户的多个角色方法(位掩码和< a href="https://github.com/ryanb/cancan/wiki/Separate-Role-Model" rel="nofollow">单独的角色模型)并且不希望设置其他模型或数据库表。
My ability model looks something like this:
class Ability
include CanCan::Ability
def initialize(user)
if user.role == "moderator"
can :manage, [Forum, Post]
elsif user.role == "admin"
can :manage, [Enrollment, SiteCare, Forum, Post]
elsif user.role == "superadmin"
can :manage, [Permission, Enrollment, SiteCare, Forum, Post]
end
end
end
In reality some of the roles have a dozen items they manage. To simplify things how can i construct some ruby that would keep me from having to duplicate so much text? Perhaps something like this construct?
class Ability
include CanCan::Ability
def initialize(user)
a = "Forum, Post"
b = "Enrollment, SiteCare"
c = "Permission"
if user.role == "moderator"
can :manage, [{a}]
elsif user.role == "admin"
can :manage, [{a + b}]
elsif user.role == "superadmin"
can :manage, [{a + b + c}]
end
end
end
Thanks.
P.S. I am aware of the multiple role per user methods (bitmask and Separate Role Model) and prefer not setting up the additional models or database tables.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我自己使用单独的角色模型。
按照你的代码模型,我可以想到一个办法。合并字符串,然后对于每个对象(用冒号分隔)使用 constantize ,所以你会得到一个常数。
连接后进行分割是必要的。您连接所有字符串,然后将每个类(论坛、帖子等)分隔成一个新字符串。完成后,您对每个字符串调用 Constantize,接收一个可以使用的常量。 「论坛」->论坛
我用 irb 进行了基本测试,没有使用 Constantize,它似乎工作正常。试试吧!
I use the Separate Role Model myself.
Following your code model, I can think of a way. Merge the strings, then for each object (separated by colons) use constantize, so you will get a constant.
The join followed by a split is necessary. You join all the strings, and then separate each class (forum, post etc.) into a new string. After that is done, you call constantize on each string, receiving a constant which you can use. "Forum" -> Forum
I did basic tests with irb without the constantize and it seems to be working fine. Try it!