Rails:使用CanCan为用户所属的每个组织分配多个角色?

时间:2013-02-21 07:10:19

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

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

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

但是,CanCan gem似乎只能解决单个组织的用户角色问题。我仍然是初学者,但从我可以收集的内容来看,CanCan gem假设用户角色仅与主应用程序绑定。

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

2 个答案:

答案 0 :(得分:8)

您认为必须将角色保存为用户模型中的字符串字段。你根本不需要:

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

答案 1 :(得分:2)

我们有类似的东西。解决方案是覆盖current_ability方法。在您的情况下,您可能有一个用户和组织的连接表。我们称之为user_organizations。在此连接表中,您可能还存储了特定组织的用户角色,对吧?所以让我们使用该表来定义当前的能力。在您的应用程序控制器中

def current_ability
  # assuming you have a current_user and current_organization method
  Ability.new UserOrganization.where(user_id: current_user.id, organization_id: current_organization.id).first
end

# ability.rb
class Ability
  include CanCan::Ability
  def initialize(user_organization)
    user_organization ||= UserOrganization.new

    case user_organization.role
    when 'admin'
    when '...'
    when nil
      # for users not a member of the organization
    end
  end
end

希望这会给你一些想法