In my app I have the following models:
Users
Groups
Permissions (user_id, group_id, role_id)
Where role_id 1: admin, 2: member
I want to make sure I'm understanding CanCan correctly. In the ability.rb file, I only want group admins (permission.role_id == 1) to be able to update/destroy/create new group permissions.
permission.role_id == 2, members, should just be able to read the group and the group's permissions. Except for having the ability to destroy their group permission.
Here is my CanCan ability.rb file:
class Ability
include CanCan::Ability
开发者_开发知识库 def initialize(current_user, groupid_viewing)
current_user ||= User.new #Guest user (not signed in)
if groupid_viewing && current_user.try(:role, groupid_viewing) == 'Admin'
can :manage, Group
can [:create, :update], Permission do |permission|
current_user.try(:role, groupid_viewing) == 'Admin'
end
class GroupsController < ApplicationController
....
def current_ability
@current_ability ||= Ability.new(current_user, params[:group_id] && params[:group_id].to_i)
end
class ApplicationController < ActionController::Base
def current_ability
@current_ability ||= Ability.new(current_user, nil) #(user, group)
end
You also need to specify the abilities for the role_id:2
.
if groupid_viewing && current_user.try(:role, groupid_viewing) == 'Member'
can :read, Group
can :destroy, Permission do |permission|
current_user.try(:role, groupid_viewing) == 'Member'
end
Also, there is no need of creating current_ability
the way you are doing.
It should be an after_create callback that should assign abilities when the Member or Admin is created.
精彩评论