ruby-on-railsrolify

Assign roles to devise user on registration with Rolify


am working on a system that requires an admin and a normal user,am trying to implement the system using devise,rolify and cancancan.My problem is i want to add an admin role to the first user that signs up on the system, but so far i can only make that happen through the rails console,i did an override of the registrations controller too. below is what i have tried so far.

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

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

Registrations Controller

   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

Solution

  • I was able to get it to work,for those who might face such issue in the future,here is my solution

    Registration controller

       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