Rails Cancan: Defining Default Role on Signup

2019-09-06 07:20发布

问题:

I've recently added roles to my rails application with CanCanCan (by enumeration)- but now I want to add a default role on signup. How do I go about doing this? Does it go in the controller or model?

My User model:

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

My Ability Model - there's just three roles, an administrator which I will create through seeding the database with a user with a role of 1- and then everyone else should be 2 on signup.:

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

回答1:

you can add callback to your model

  before_create :set_default_role

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

devise article

or in your case you can do

 before_create :set_default_role

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