1

I am trying to assign default role for new users with CanCan gem. Administrator can assign multiple roles to a user. In order to do this I added the following code:

# User's role handler (More information: https://github.com/ryanb/cancan/wiki/role-based-authorization)
# This will perform the necessary bitwise operations to translate an array of roles into the integer field
ROLES = %w[admin moderator user banned].freeze

def roles=(roles)
  self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r)}.inject(0, :+)
end

def roles
  ROLES.reject do |r|
    ((roles_mask.to_i || 0) & 2**ROLES.index(r)).zero?
  end
end

# Role Inheritance
def role?(base_role)
  ROLES.index(base_role.to_s) <= ROLES.index(role)
end

# Check the user's roles
def is?(role)
  roles.include?(role.to_s)
end

I want to define the default user role (which is :user) and I found this question: Rails Cancan: Defining Default Role on Signup . It says that I have to simple add set_default_role method:

before_create :set_default_role

private
  def set_default_role
    self.role ||= Role.find_by_name('your_role')
  end

But the problem that I am using a different approach of adding a new role. I have to store an integer instead of a string. Also, when you assign a role to the user, it stores an specific index to the users table. My idea was to add default: 4 value to the roles column in the database but I've noticed that adding new roles to the database changes the user index number. In other words if user role was equal to 4, after update it will be 8 (for example).

The question is how to assign the default role to the user?

Thank you very much for your help and time!

Anton S.
  • 969
  • 1
  • 11
  • 29
  • Cancan gem is old. I think, you should use cancancan gem instead of cancan gem. -> https://github.com/CanCanCommunity/cancancan – Hamdi Bayhan Feb 01 '18 at 21:26
  • @hamdi thank, I will switch then... anyways the approach is still the same :) – Anton S. Feb 01 '18 at 21:28
  • I think you should use enum values for user roles. You can find more details in the below link for Role Based Authorization: https://github.com/CanCanCommunity/cancancan/wiki/Role-Based-Authorization – Hamdi Bayhan Feb 01 '18 at 21:40
  • @hamdi probably you are right. I just followed `wiki` page on `CanCan`. Thank you very much. – Anton S. Feb 01 '18 at 21:45

0 Answers0