一个用户可以属于许多组织。我希望用户能够为其所属的每个组织分配不同的角色/授权。
例如,用户“kevin”可能属于组织“stackoverflow”和“facebook”。kevin 应该能够成为 stackoverflow 的管理员和 facebook 的普通成员(读+写)。
但是,CanCan gem 似乎只针对单个组织的用户角色。我仍然是初学者,但据我所知,CanCan gem 假定用户角色仅与主应用程序相关联。
我如何能够为不同的组织分配不同的角色,最好使用 CanCan gem?
一个用户可以属于许多组织。我希望用户能够为其所属的每个组织分配不同的角色/授权。
例如,用户“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
我们有这样的东西。解决方案是覆盖 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
希望这能给你一些想法