如何为具有多个角色的用户限制load_resource?

时间:2012-05-11 21:52:02

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

在我的应用程序中,所有用户都可以阅读自己的任务。第二个控制器仅适用于主持人,主持人可以查看所有任务。

# accessible for every user
# every user should see only own tasks, 
# but at the moment all moderators see all tasks
class TasksController < ActionController::Base
  load_and_authorize_resource
end

# only accessible for moderators, all tasks
class TasksModeratorController < ActionController::Base
  load_and_authorize_resource :task, :parent => false
end


# Ability
# Moderators can read all tasks
if user.moderator?
  can :read, Task
end
# All users can read there own tasks
can :read, Task, :user_id => user.id

如何限制TasksController中的任务,以便只向管理员显示自己的任务,但在TasksModeratorController中显示所有任务?或者有更常见的方法来处理这个问题吗?

1 个答案:

答案 0 :(得分:1)

能力是一种模型,因为通常访问权限与控制器无关。但是,如果不是通过current_ability将控制器传递给能力初始化器来使其明确。 我认为鼓励这种将更多信息传递给能力的做法。所以我未经测试的2美分

# in ApplicationController
def current_ability
  @current_ability ||= Ability.new(current_user, self)
end

# in Ability
def initialize(user, controller)

# all same as before ...
# Moderators can read all tasks if using TasksModeratorController or any subclass
if user.moderator? && controller.is_a?(TasksModeratorController)
  can :read, Task
end

# All users can read there own tasks
can :read, Task, :user_id => user.id