Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on rails, cancan and default role assignment

I have built a small ruby webservice, in this I have implemented cancan authorization.

I followed this tutorial. The problem is that, I can't find out the way to assign at the user, when they do the registration to my site, the base role level.

I find out to do this with a checkbox, but it's not what I want. My idea was to put this assignment directly into the registrations_controller, but I failed to save the role.

I hope that somebody can help me.

Thank you.

like image 496
Marco Fedele Avatar asked Apr 21 '26 11:04

Marco Fedele


2 Answers

This is what worked for me

user.rb:

  after_create :default_role

  private
  def default_role
    self.roles << Role.where(:name => 'User').first
  end
like image 78
Ivailo Bardarov Avatar answered Apr 24 '26 07:04

Ivailo Bardarov


I had the same problem, but I am using embedded association from rbates: http://railscasts.com/episodes/189-embedded-association

user.rb:

before_create :default_role

private
def default_role
 self.roles = ['client']
end

Works like a charm, but pay attention that the hook is before_create, not after_create, because the before_create runs just before the insert operation.
The after_create is after the insert operation, which in my case is late.

like image 34
Nuno Avatar answered Apr 24 '26 07:04

Nuno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!