只有具有所有者角色的用户才能发送邀请

Only Users with Owner Role can send invitation

我正在使用 Rolify、Devise、CanCanCan 和 devise_invitable,设置非常完美,我有两个角色 "owner" 和 "member",我有 3 个模型,用户,项目和 Gig,用户 has_many 项目和项目 has_many Gig 反之亦然,我的问题是,我如何确保只有角色 "owner" 的用户才能向新用户发送邀请。

Ability.rb

  def initialize(user)
    # Define abilities for the passed in user here. For example:
    #
       user ||= User.new 

      if user.has_role? :owner
        can :invite, User
        can :manage, Project, user_id: user.id
      elsif user.has_role? :member
        can :manage, Gig, user_id: user.id
      else
        can :manage, Project
      end

role.rb

class Role < ApplicationRecord
has_and_belongs_to_many :users, :join_table => :users_roles


belongs_to :resource,
           :polymorphic => true,
           :optional => true


validates :resource_type,
          :inclusion => { :in => Rolify.resource_types },
          :allow_nil => true

scopify
end

user.rb

class User < ApplicationRecord

  resourcify
  rolify 

  has_many :projects,dependent: :destroy
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :invitable, :database_authenticatable, :confirmable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

end

invitations_controller

 class InvitationsController < Devise::InvitationsController
    before_action :is_owner?, only: [:new, :create]

    private 
    def is_owner?
        current_user.has_role? :owner
    end
end

为了可能遇到此类问题的其他人的利益,这是我的工作方式,像这样修改 invitations_controller。

class InvitationsController < Devise::InvitationsController
   def new
     if cannot?( :invite, User )
       raise CanCan::AccessDenied
     else
       build_resource
       resource.practice_id = current_practice_id
       render_with_scope :new
     end
   end
   def create
     if cannot?( :invite, User )
       raise CanCan::AccessDenied
     else
       super
     end
   end
end