康康宝石简单问题
models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
if user.role? :admin
can :manage, :all
else
can :read, :all
can :create, Comment
can :update, Comment do |comment|
comment.try(:user) == user || user.role?(:moderator)
end
if user.role?(:author)
can :create, Article
can :update, Article do |article|
article.try(:user) == user
end
end
end
end
end
在 Railscasts 中有方法 user.role? :管理员和if user.role?(:author).我不明白。我是否需要在模型中创建一个方法才能使其工作?
我将角色存储在用户表中作为角色列。
models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user
if user.role? :admin
can :manage, :all
else
can :read, :all
can :create, Comment
can :update, Comment do |comment|
comment.try(:user) == user || user.role?(:moderator)
end
if user.role?(:author)
can :create, Article
can :update, Article do |article|
article.try(:user) == user
end
end
end
end
end
In Railscasts there are methods user.role? :admin & if user.role?(:author).I dont get it. Do i need to create a method in model to make it work?
I'm storing roles in Users table as a role column.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,你需要自己写这个。不过,CanCan 项目有一个 wiki 页面描述如何执行此操作。
维基百科的第一行说:
我几乎完全不同意该页面上使用
role_mask
的示例,但该页面仍然很好,应该给您一些想法。还有 单独的角色模型示例,我个人更喜欢它。这取决于你想将角色存储在哪里信息。
Yes, you need to write this yourself. However, the CanCan project has a wiki page describing how to do this.
The first line of the wiki says:
Note that I disagree almost completely with the example on that page that uses a
role_mask
, but the page is still good and should give you some ideas.There is also the Separate Role Model example, which I personally like better. It depends on where you want to store your role information.
如果您正在寻找即插即用的 gem,那么请查看声明性授权。
Raynb 说他开发 Cancan 是因为 DA 对于这里的某些项目来说太过分了:http: //railscasts.com/episodes/192-authorization-with-cancan?autoplay=true
If you're looking for a gem that is plug-and-play, then check out Declarative Authorization.
Raynb says that he developed Cancan because DA was overkill for some projects here: http://railscasts.com/episodes/192-authorization-with-cancan?autoplay=true