我想使用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是一个嵌套的联盟资源。我想要做的是允许用户修改联盟,并根据存储在league_relation中的数据来衡量每个用户的授权。然后,我希望用户修改联盟关系,只基于用户模型中存储的数据。
简而言之:我基本上希望LeagueRelations用于授权联盟操作,用户用于授权LeagueRelations操作。例如,league_relation.owner = true删除联盟,但是user.owner?必须为true才能删除LeagueRelation。在联盟控制器内部如何根据league_relation的属性进行授权,以及在其他机型上的其他控制器中授权其他操作。如果你需要更多的澄清,请留下评论。
谢谢。
发布于 2011-08-19 13:42:51
好了,我解决了这个问题。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/ 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需要注意的一点是,这依赖于应用程序控制器调用子类中的方法。希望这能有所帮助!
https://stackoverflow.com/questions/7102351
复制相似问题