ruby-on-rails - rails : Using CanCan to assign multiple roles to Users for each organization they belong to?

标签 ruby-on-rails ruby-on-rails-3 gem authorization cancan

一个用户可以属于许多组织。我希望用户能够为其所属的每个组织分配不同的角色/授权。

例如,用户“kevin”可能属于组织“stackoverflow”和“facebook”。 kevin 应该能够成为 stackoverflow 的管理员和 facebook 的普通成员(读+写)。

但是,CanCan gem 似乎只针对单个组织的用户角色。我仍然是初学者,但据我所知,CanCan gem 假定用户角色仅与主应用程序相关联。

我如何能够为不同的组织分配不同的角色,最好使用 CanCan gem?

最佳答案

您认为您必须将角色保存为 User 模型中的字符串字段。您根本不必:

class User
  has_many :roles
end

class Role
  belongs_to :user
  belongs_to :organization
  attr_accessible :level
end

class Ability
  def initialize(user)
    can :read, Organization
    can :manage, Organization do |organization|
      user.roles.where(organization_id:organization.id,level:'admin').length > 0
    end
    can :write, Organization do |organization|
      user.roles.where(organization_id:organization.id,level:'member').length > 0
    end
  end
end

关于ruby-on-rails - rails : Using CanCan to assign multiple roles to Users for each organization they belong to?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14996479/

相关文章:

ruby-on-rails - APNS Houston gem 移动到配置文件

ruby-on-rails - ActiveRecord::Relation 上的类方法调用如何获取上下文?

mysql - LoadError using MySQL with ruby​​ (mysql_api.so not found)

ruby-on-rails - Activeadmin 可按多列排序

ruby-on-rails - 继承的资源和 Mongoid

ruby-on-rails - 如何使用 docker 捆绑安装本地路径 gem?

ruby-on-rails - nokogiri gem 安装问题

ruby - 如何在 Debian Linux for ARM 上运行 pry

ruby-on-rails - 在 Ruby 中使用 HMAC SHA256

ruby-on-rails - 使用 cancan 和 rolify 进行角色管理