Skip to content

How To: Add a default role to a User

DVG edited this page Jul 10, 2012 · 8 revisions

Add a role to the User Model

Set up the Role and User models

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

$ 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

Set up seeds.rb with your roles

['registered', 'banned', 'moderator', 'admin'].each do |role|
  Role.find_or_create_by_name role
end

Then

$ rake db:seed

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
    if self.role.nil?
      self.role = Role.find_by_name('registered')
    end
  end
end
Clone this wiki locally