与Rolify,Devise,CanCanCan和devise_invitable合作,设置非常完美,我有两个角色“所有者”和“成员”,我有3个模型,User,Project和Gig,User has_many Project and Project has_many反之亦然,我的问题是,我如何确保只有具有角色“所有者”的用户才能向新用户发送邀请。
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
答案 0 :(得分:0)
为了其他可能遇到此类问题的人的利益,以下是我如何使用它,修改这样的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