1
votes

I am using devise for my authentication system and cancan for permissions. I am in the process of adding roles and I am trying to have it so when a user signs up he will automatically be assigned a role. I watched ryan bate screencast and also followed a devise & cancan tutorial .

How I can implement this without using check boxes and automatically assign a role to user based upon when they're signing up.

2

2 Answers

3
votes

You could try using a callback: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

The before_create callback is probably what you want in your user model:

class User < ActiveRecord::Base
  before_create :set_default_roles
  private
    def set_default_roles
      self.roles = ['Default user']
    end
end
2
votes

AR::Callbacks does the trick for you, however I prefer setting up roles when User object is firstly initialised:

class Role < ActiveRecord::Base
end

class User < ActiveRecord::Base
  after_initialize :set_default_roles

  private
    def set_default_roles
      self.roles = self.roles || [Role.find_by_name('Default Role')]
    end
end