自己的一个 Rails 项目,权限控制使用 cancancan 2.0
代码如下
class Ability
include CanCan::Ability
attr_reader :user
def initialize(u)
@user = u
if @user.blank?
roles_for_anonymous
elsif @user.roles?(:admin)
can :manage, :all
elsif @user.roles?(:member)
roles_for_member
else
roles_for_anonymous
end
end
protected
def roles_for_member
can :create, Project
can [:update,:destroy], Project, user_id: user.id
end
## ...
end