1

在我的应用程序中,所有用户都可以在那里阅读自己的任务。第二个控制器仅供版主使用,版主可以查看所有任务。

# 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 中的所有任务?还是有更常见的方法来处理这个?

4

1 回答 1

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
于 2012-05-11T22:38:12.667 回答