-
Notifications
You must be signed in to change notification settings - Fork 5.5k
How To: Add a default role to a User
rkorzen edited this page Aug 2, 2016
·
8 revisions
First create the Role model and link it to the User Model
$ rails g model Role name:string
$ rails g migration addRoleIdToUser role:references
$ rake db:migrate
Then in your Models
class User < ActiveRecord::Base
belongs_to :role
end
class Role < ActiveRecord::Base
has_many :users
end
['registered', 'banned', 'moderator', 'admin'].each do |role|
Role.find_or_create_by({name: role})
end
Then
$ rake db:seed
class User < ActiveRecord::Base
belongs_to :role
before_create :set_default_role
# or
# before_validation :set_default_role
private
def set_default_role
self.role ||= Role.find_by_name('registered')
end
end