Reputation: 4546
I am trying to add a user role according to Rolify gem in my devise User model.
What I basically want to achieve is that, if the user has selected that he is a student or a teacher in the registration page itself, after the creation of the user, it should add the required roles to the user.
Please note that I am not storing the 'role' in the User table. I am just using attr_accessor to send me an initial value to compare.
This is my User model code :
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255) default(""), not null
# encrypted_password :string(255) default(""), not null
# reset_password_token :string(255)
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default(0), not null
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# avatar :string(255)
# username :string(255)
#
class User < ActiveRecord::Base
# This is for the user roles.
rolify
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessor :role
# Adding the carrierwave uploader
mount_uploader :avatar, AvatarUploader
before_create :add_specified_role
def add_specified_role
if self.role == 0
# I am sure I am messing it up here and this is not the way.. :/
after_create :add_student_role
elsif self.role == 1
after_create :add_teacher_role
end
end
def add_student_role
self.add_role(:student) if self.roles.blank?
end
def add_teacher_role
self.add_role(:teacher) if self.roles.blank?
end
end
However, it does not seem to be working as when I check the roles, the role has not been added and I am sure I am doing something wrong.
What is the correct way to achieve the above task?
Upvotes: 0
Views: 38
Reputation: 1541
callback should be
after_create :add_specified_role , if: proc { |a| a.roles.blank? }
instead of
before_create :add_specified_role
And method should
def add_specified_role
if role == 0
add_role(:student)
elsif role == 1
add_role(:teacher)
end
end
Upvotes: 0