【问题标题】:Only Users with Owner Role can send invitation只有拥有所有者角色的用户才能发送邀请
【发布时间】:2018-04-10 15:54:40
【问题描述】:

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

能力.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

invitations_controller

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

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

【问题讨论】:

    标签: ruby-on-rails cancancan rolify devise-invitable


    【解决方案1】:

    为了其他可能遇到此类问题的人的利益,这是我的工作方式,像这样修改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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-16
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 2016-03-19
      • 2023-03-21
      • 2021-01-19
      相关资源
      最近更新 更多