简体   繁体   English

使用cancan和rolify进行角色管理

[英]Role management with cancan and rolify

i'm using a devise-cancan-rolify setup to handle users. 我正在使用devise-cancan-rolify设置来处理用户。 on signup, they receive a Reader role. 在注册时,他们会收到读者角色。 I want to be able to, from an admin interface, promote them to a Writer role. 我希望能够从管理界面将它们提升为Writer角色。 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. 问题是,role和users_roles表的设置方式使得这一点变得相当复杂,特别是因为没有users_roles模型而且我非常业余。 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. 我希望你确实看到了关于设计+ cancan + rolify设置的本教程

You should have users, roles and users_roles table if you did follow these steps. 如果您按照这些步骤操作,则应该拥有users,roles和users_roles表。 You dont need users_roles model. 你不需要users_roles模型。

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: 如果这对您有用,那么现在您需要为新用户分配读者角色,最好的地方就是这样做,是after_create回调:

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 只需在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. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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