wh3wiw
Last Updated: February 25, 2016
·
356
· devatotech

Devise Roles and Default Role

First create the Role model and link it to the User Model

rails g model Role name:string
rails g migration addRoleIdToUser role_id:integer
rake db:migrate

Then in your Models:

class User < ActiveRecord::Base
  belongs_to :role
end
class Role < ActiveRecord::Base
  has_many :users
end

Setup some seeds for your roles:

['registered', 'banned', 'moderator', 'admin'].each do |role|
  Role.find_or_create_by({name: role})
end

Set up the default role as a model callback

class User < ActiveRecord::Base
  belongs_to :role
  before_create :set_default_role

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