Rails Cancan: Defining Default Role on Signup

僤鯓⒐⒋嵵緔 提交于 2019-12-12 05:39:12

问题


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


来源:https://stackoverflow.com/questions/37911060/rails-cancan-defining-default-role-on-signup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!