[英]Assign roles to devise user on registration with Rolify
我正在一個需要管理員和普通用戶的系統上工作,試圖使用devise,rolify和cancancan來實現該系統。我的問題是我想向注冊該系統的第一個用戶添加一個管理員角色,但是到目前為止,我只能通過Rails控制台實現這一目標,我也對注冊控制器進行了覆蓋。 以下是到目前為止我嘗試過的。
User.rb
class User < ApplicationRecord
resourcify
rolify
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :invitable, :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
角色
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
注冊主管
class RegistrationsController < Devise::RegistrationsController
def create
super
@number_of_users = User.all.count
if @number_of_users == 0
resource.add_role :admin
end
end
end
我能夠使它正常工作,對於那些將來可能會遇到此類問題的人,這是我的解決方案
注冊控制器
after_action :assign_role, only:[:create]
def assign_role
@number_of_users = User.all.count
if @number_of_users == 1
current_user.add_role :admin
end
end
我喜歡公認的解決方案,但為了使事情井井有條,我將其放在用戶模型中,如下所示:
after_create :assign_role
def assign_role
if User.all.count == 1
User.first.add_role :admin
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.