模型/能力.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? :admin & if user.role?(:author).我不明白。我是否需要在模型中创建一个方法才能使其工作?
我将角色存储在用户表中作为角色列。