我想使用 CanCan 来处理我的权限。我的网站有许多不同的权限级别,其中大多数都是上下文感知的。例如,以下是我的 3 个主要模型中的关系:
class User < ActiveRecord::Base
has_many :league_relations
has_many :leagues, :through => :league_relations
end
class League < ActiveRecord::Base
has_many :league_relations
has_many :users, :through => :league_relations
end
class LeagueRelation < ActiveRecord::Base
belongs_to :user
belongs_to :league
end
请注意,LeagueRelations 是 Leagues 的嵌套资源。我想要做的是允许用户修改联赛,并根据 league_relation 中存储的数据评估每个用户的授权。然后,我希望用户仅根据用户模型中存储的数据来修改联赛关系。
简而言之:我基本上希望使用 LeagueRelations 来授权 League 操作,并使用 Users 来授权 LeagueRelations 操作。即 league_relation.owner = true 删除联赛,但 user.owner?必须为 true 才能删除 LeagueRelation。如何在联盟控制器内部根据 league_relation 的属性进行授权,并在其他模型上的其他控制器中授权其他操作。如果您需要更多说明,请发表评论。
Thanks.
好的,我解决了问题。 CanCan 自述文件的开头简要提到了我的用例,但我错过了。您可以在 app/models/ 中定义新的能力类,该类接受除 current_user 之外的不同参数。为此,您将以下内容放入控制器中:
def current_ability
if params[:controller] == 'leagues'
@current_ability = LeagueAbility.new(current_user_league_relation)
elsif params[:controller] == 'league_relations'
@current_ability = LeagueRelationAbility.new(current_user_league_relation)
else
@current_ability = Ability.new(current_user)
end
end
现在您可以在 app/models/ 中创建 league_ability.rb。
class LeagueAbility
include CanCan::Ability
def initialize(league_relation)
league_relation ||= LeagueRelation.new
if league_relation.owner?
can :manage, League, :id => league_relation.league_id
elsif league_relation.moderator?
can :manage, League, :id => league_relation.league_id
cannot [:delete, :destroy], League
else
can :read, League
can :create, League
end
end
end
需要注意的一件事是,这依赖于您的应用程序控制器调用子类中的方法。希望有帮助!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)