Question

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!

Was it helpful?

Solution

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!

OTHER TIPS

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.

I would like to point out that the method used in Danny's answer doesn't work for me in Rails 4

What I found to work is putting this into your seeds.rb file

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

This seems to do what you asked for me using Rails 4! This was based off of this answer above

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top