0
我想在我的设计用户模型中根据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
然而,它似乎并没有工作,当我检查的角色,作用还没有被加入,我相信我做错了什么。
什么是实现上述任务的正确方法?
我不存储用户表中的 '角色'。所以它不会出现在after_create回调函数中,因为没有带'role'的列,因此after_create在当前场景中不起作用。我不想在用户表中存储另一个角色列,因为它会使Rolify gem的整个目的无用。 –
@SankalpSingha在用户表中存储另一个角色意味着? ,Rolfiy为你做了,你已经添加了'attr_accessor:role'这不是表字段 –
@SankalpSingha rolify将角色存储在另一个角色表中has_and属于许多与用户的关联 –