ruby-on-railsauthorizationcancancan

CanCanCan ability to create Invite resource if User can manage Group


I have the following Group ability defined:

# Group abilities
can :manage, Group do |group|
  user.in_group?(group, as: :owner)
end

what I would like for the Invite is something like:

can :manage, Invite do |invite|
  can?(:manage, invite.group)
end

In other words, I would like to support users having the ability to create Invites for a group they are an owner of. Since groups can have multiple owners (via a GroupMemberships object), I can't use the simple association hash rules. I also can't use a block because there isn't an instance of @invite in InvitesController#create.

How would you go about writing an ability rule for this scenario?


Solution

  • can :manage, Invite, group: { group_memberships: { user: user, membership_type: 'owner' } }
    

    is the ability that ended up working for the create action with the following CanCanCan hooks in the controller:

    class InvitesController < ApplicationController
      load_and_authorize_resource :group
      authorize_resource :invite, through: :group