一个用户可以属于许多组织。我希望用户能够为其所属的每个组织分配不同的角色/授权。
例如,用户“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/