2013-04-02 35 views
0

我在Rails應用程序中使用CanCan支持Rails Admin。儘管我對一個問題感到困惑。 CanCan如何知道用戶登錄的是什麼?例如,我的用戶可以有不同的角色,通過CanCan,我可以爲每個表的某些訪問分配角色。當我去localhost:3000/admin,我收到錯誤瞭解CanCan能力和用戶

CanCan::AccessDenied in RailsAdmin::MainController#dashboard 

Ability.rb文件

def initialize(user) 
    if user and user.role.eql? :super_admin 
     can :manage, :all    # allow superadmins to do anything 
    elsif user and user.role.eql? :admin 
     can :manage, [Location, School] # allow admins to manage only Locations and Schools 
    end 
    end 

所以,我該怎麼辦,這樣用戶必須登錄到Rails管理的能力嗎?我必須手動創建它嗎?

回答

1

您需要在控制器中使用current_user方法。假設你有這個功能,如果你沒有簽名,你將無法訪問當前用戶,所以如果你的能力文件不存在,你需要分配一個用戶。在您的initialize方法中,如果用戶不存在,請添加user ||= User.new以進行分配。

def initialize(user) 
    user ||= User.new 

    if user and user.role.eql? :super_admin 
    can :manage, :all    # allow superadmins to do anything 
    elsif user and user.role.eql? :admin 
    can :manage, [Location, School] # allow admins to manage only Locations and Schools 
    end 
end 
+0

啊。我認爲這可能是它,但無法在文檔中驗證。謝謝。 – jason328

+0

沒問題,@ jason328!很高興我能幫上忙! –

2

默認情況下,康康舞會使用任何由current_user返回。如果您在名稱空間內使用Devise(例如admin),則Devise實際上將使用current_admin_user。您可以在ApplicationController(或某個其他基本控制器)中創建一個current_user方法,該方法返回current_admin_user或覆蓋current_ability方法,用current_admin_user來替代實例化Ability。

(這是所有假設你的設計是使用一個命名空間。默認情況下,設計將使用current_user