我正在尝试根据我的设计用户模型中的Rolify gem添加用户角色。
我基本上想要实现的是,如果用户在注册页面本身中选择了他是学生或教师,则在创建用户之后,它应该向用户添加所需的角色。
请注意,我没有在“用户”表中存储“角色”。我只是使用attr_accessor向我发送一个初始值进行比较。
这是我的用户型号代码:
# == 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
然而,它似乎没有起作用,因为我检查角色,角色没有被添加,我确信我做错了什么。
实现上述任务的正确方法是什么?
答案 0 :(得分:0)
after_create :add_specified_role , if: proc { |a| a.roles.blank? }
而不是
before_create :add_specified_role
方法应该
def add_specified_role
if role == 0
add_role(:student)
elsif role == 1
add_role(:teacher)
end
end