Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add roles rolify using cancan and devise?

I get that there are a lot of questions on this subject but none have really answered what i'm looking for.

I'm attempting to use rolify to define my roles in cancan, i was able to make an admin role via rails console and set the default role for new users.

My question is how do i set a batch of roles to different values and assign those roles to certain users?

If you have a good tutorial that explains this process that would help as well, screencasts preferred.

thanks!

like image 969
Gregg Horton Avatar asked Jan 05 '14 03:01

Gregg Horton


2 Answers

How do you create a batch of roles?

You can do this in your db/seeds.rb file, which is executed each time you run rake db:seed

[:admin, :author, :contact, :user].each do |role|
  Role.find_or_create_by_name({ name: role }, without_protection: true)
end

Adding a role to someone is done like

@user.add_role :admin

You check whether a user has a certain role using

@user.has_role? :admin

And, as Steve already said, the https://github.com/EppO/rolify documentation should get you on the move!

like image 168
Danny Avatar answered Sep 29 '22 19:09

Danny


I imagine your question is more complicated than this, but the simple answer is that you use add_role. You don't have to do anything to create the roles other than assign them to something. So if Jane is globally an admin and Joe is a peon, you could just use:

User.where(name: 'Joe').add_role :peon
User.where(name: 'Jane').add_role :admin

You can also add roles with respect to specific classes or instances of classes, but the above was the most direct answer to your question. The README on github is pretty decent as tutorials go.

like image 33
Steve Rowley Avatar answered Sep 29 '22 21:09

Steve Rowley