简体   繁体   中英

Role management with cancan and rolify

i'm using a devise-cancan-rolify setup to handle users. on signup, they receive a Reader role. I want to be able to, from an admin interface, promote them to a Writer role. Problem is, the way the roles and users_roles tables are set up make this rather complicated, especially as there is no users_roles model and I'm fairly amateur. Is there anyone familiar with this who can guide me the right way here?

I hope you did see this tutorial about devise + cancan + rolify setup.

You should have users, roles and users_roles table if you did follow these steps. You dont need users_roles model.

First thing you need to do, is to be sure sure that you can assign, and check roles for users.

You should able to run these codes before continuing (from usage part of documentation, try these in console, on any user)

user.add_role "admin"
user.has_role? :admin

If this is working for you, now you need to assign reader role for new users, best place to do this, is after_create callback:

class User
  after_create :assign_reader_role
private
  def assign_reader_role
    self.add_role "reader"
  end
end

Next step is to create add / remove writer roles from admin interface.

Simply add two actions in your UsersController

def assign_writer_role
  @user = User.find(params[:id])
  @user.add_role "writer"
  redirect_to @user
end

def remove_writer_role
  @user = User.find(params[:id])
  @user.remove_role "writer"
  redirect_to @user
end

thats all.

i hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM