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!