【发布时间】:2016-11-26 11:22:22
【问题描述】:
我正在尝试根据我的设计用户模型中的 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
但是,当我检查角色时,它似乎不起作用,角色尚未添加,我确定我做错了什么。
完成上述任务的正确方法是什么?
【问题讨论】:
标签: ruby-on-rails ruby devise rolify