2012-05-14 34 views
0

我的問題是絕對理論的,就像「這是正確的事情嗎?」。 我是Rails的新手,尤其是Ruby,我試圖在我的Rails應用中使用Cancan自動化解決方案。坎康能力定義:整個控制器作爲一個對象

讓我們考慮一下這樣一個簡單的控制器,一對關聯的視圖和一個帶有DB表的用戶模型。

class UsersController < ApplicationController 
    def index 
    @users = User.all 
    end 
    def show 
    @user = User.find(params[:id]) 
    end 
end 

的目標是限制訪問「指數」的方法,但所有管理員和允許普通用戶只能看到他們自己的網頁,例如允許id = 5的用戶看到「users/5」頁面。 對於這個範圍,我已經爲康康創建了一個能力類。那就是:

class Ability 
    include CanCan::Ability 

    def initialize user, options = {} 
    default_rules 
    if user 
     admin_rules(user) if user.role.eql? "admin" 
     player_rules(user) if user.role.eql? "player" 
    end 
    end 

    def admin_rules user 
    can :read, UsersController 
    end 

    def player_rules user 
    can :read, User do |user_requested| 
     user_requested.id == user.id 
    end 
    end 

    def default_rules 
    end 
end 

我的問題是: 我應該使用UsersController如「可以」方法的對象,如果我沒有類型用戶的方便嗎?稍後在控制器的「索引」方法中使用「authorize!:show,UsersController」。或者它應該以其他方式完成? 謝謝你的建議。

回答

1

不,你不希望將UsersController添加到慘慘。

CanCan旨在授權資源,而不是Rails控制器。

我建議如下:

def initialize(user) 
    if user.is_admin? 
    can :manage, User 
    else 
    can :manage, User, :id => user.id 
    end 
end 

這將允許用戶僅他自己的用戶訪問,除非他是管理員。 查看在CanCan Wiki的頁面Defining abilities

0

我用一個符號,例如,在能力類

def initialize(user) 
    if user.is_admin? 
    can :any, :admin 
    end 
end 

,並在控制器

authorize! :any, :admin 
0

+1 to @Tigraine,(尚未達到15聲望)。

按照第load_and_authorize_resource他的指示...

class Ability 
    include CanCan::Ability 

    def initialize user, options = {} 
    default_rules 
    if user 
     admin_rules(user) if user.role.eql? "admin" 
     player_rules(user) if user.role.eql? "player" 
    end 
    end 

    def admin_rules user 
    can :manage, User 
    end 

    def player_rules user 
    can :manage, User :id => user.id 
    end 

    def default_rules 
    end 
end 

,並在控制器中做到這一點...

class UsersController < ApplicationController 
    load_and_authorize_resource 
    # => @users for index 
    # => @user for show 

    def index 
    end 
    def show 
    end 
end 

詳情見的this link

+0

謝謝,這很有用。 – user1261595

0

在底部維基我找到了另一種設置能力的方法。這是一種先進的,check it out here

ApplicationController.subclasses.each do |controller| 
     if controller.respond_to?(:permission) 
      clazz, description = controller.permission 
      write_permission(clazz, "manage", description, "All operations") 
      controller.action_methods.each do |action| 
... 
相關問題