2012-05-11 78 views
1

在我的應用程序中,所有用戶都可以讀取自己的任務。第二個控制器僅適用於主持人,主持人可以看到所有任務。Howto限制多個角色的用戶的load_resource?

# 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

能力是一種模型,因爲通常訪問權限是獨立於控制器的。但是,如果不是通過將控制器通過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