Только пользователи с ролью владельца могут отправлять приглашения

Я работаю с Rolify, Devise, CanCanCan и devise_invitable, настройка была идеальной, у меня есть две роли «владелец» и «участник», и у меня есть 3 модели: пользователь, проект и концерт, пользователь имеет проект has_many и проект has_many Gig, наоборот , мой вопрос в том, как я могу гарантировать, что только пользователи с ролью «владелец» могут отправлять приглашения новому пользователю.

Способность.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

роль.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

пользователь.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

приглашения_контроллер

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

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

person chrisgeeq    schedule 10.04.2018    source источник


Ответы (1)


В интересах других, которые могут столкнуться с такой проблемой, вот как я это сделал, измените приглашения_контроллера следующим образом.

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
person chrisgeeq    schedule 10.04.2018