Rails Cancan:在注册时定义默认角色

我最近使用CanCanCan(通过枚举)为我的rails应用程序添加了角色 – 但现在我想在注册时添加默认角色。 我该怎么做呢? 它是在控制器还是模型中?

我的用户型号:

class User < ActiveRecord::Base #Defining different roles enum role: [:Admin, :User, :Guest] #Users can only create one scholarship application has_one :applications # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable end 

我的能力模型 – 只有三个角色,一个管理员,我将通过为一个角色为1的用户播种数据库来创建,然后其他人应该在注册时为2:

 class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user (not logged in) if user.role = 1 can :manage, :all elsif user.role = 2 can :manage, Application can :manage, User else can :read, Static_Page end end end 

您可以为模型添加回调

  before_create :set_default_role private def set_default_role self.role ||= Role.find_by_name('your_role') end 

设计文章

或者在你的情况下,你可以做到

  before_create :set_default_role def set_default_role self.update_attribute(:role,'your_role') end