Ruby on rails, cancan and default role assignment

故事扮演 提交于 2020-01-03 20:13:32

问题


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.


回答1:


This is what worked for me

user.rb:

  after_create :default_role

  private
  def default_role
    self.roles << Role.where(:name => 'User').first
  end



回答2:


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.




回答3:


I have rebuild the migration, I have unified the user and role tables, so now I can assign all without problem.

Thank you.



来源:https://stackoverflow.com/questions/6052504/ruby-on-rails-cancan-and-default-role-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!