【问题标题】:Rails: Using CanCan to assign multiple roles to Users for each organization they belong to?Rails:使用 CanCan 为用户所属的每个组织分配多个角色?
【发布时间】:2013-02-06 10:27:31
【问题描述】:

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

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

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

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

【问题讨论】:

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


    【解决方案1】:

    我们有这样的东西。解决方案是覆盖 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
    

    希望这能给你一些想法

    【讨论】:

      【解决方案2】:

      您认为必须将角色保存为 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
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-08
      • 2012-11-02
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多