2013-07-02 62 views
0

我有一個用戶模型,用布爾開關來指定admin t/f。我目前的應用控制器:設計/ cancan重定向管理問題

class ApplicationController < ActionController::Base 
    protect_from_forgery 

    def after_sign_in_path_for(user) 
    if current_user.admin? 
     admin_index_path 
    else 
     dashboard_index_path 
    end 
    end 
end 

我當前的管理控制器:

class AdminController < ApplicationController 

    def index 
     if current_user.admin? 

      admin_index_path 
     else 

      home_index_path 
     end 
    end 
end 

我們的目標當然是只允許訪問管理員索引頁,以管理員用戶。當我以管理員身份登錄時,重定向工作正常,但當我以非管理員用戶(未定義方法「admin?」for nil:NilClass)導航到admin_index_path時,我在AdminController#index錯誤中收到NoMethodError。幫助解決這個問題?我覺得可能有一個更加優雅和安全的CanCan解決方案,但是我還沒有找到如何實現這一點的很好解釋。思考?提前致謝!

+0

您收到此消息是因爲您沒有current_user。它只是指向零。這對我來說似乎很奇怪,因爲如果你使用設計,它必須指向用戶。你是否在某處重寫current_user? –

+0

啊我想我明白了。我實際上試圖導航到管理路徑,而沒有以任何用戶身份登錄。這可能是它拋出這個錯誤的原因。不知道如何處理未登錄的用戶,因爲我不需要登錄即可使用該應用程序。思考? – settheline

回答

0

使用的before_filter

https://github.com/plataformatec/devise#controller-filters-and-helpers

class AdminController < ApplicationController 

before_filter :authenticate_user!, only: [:index] 
before_filter :is_admin, only: [:index] 

def index 
end 

private 

    def is_admin 
    if user_signed_in? 
    if current_user.admin? 
    true 
    else 
    redirect_to home_index_path 
    end 
    else 
    redirect_to login_path 
    end 
end 

end 

user_signed_in?檢查用戶是否有登錄和 current_user.admin?檢查管理員訪問時指數

def is_admin 
if current_user.nil? 
    redirect_to login_path 
else 
    if current_user.admin? 
    true 
    else 
    redirect_to home_index_path 
    end 
end 
end 
0

使用的資源,而不是使用它更通用

def after_sign_in_path_for(resource) if current_user.admin? admin_index_path 其他 dashboard_index_path 結束 結束 和

,只是把 的before_filter:的authenticate_user!在索引行動。它會解決你的問題。 因爲current_user變量沒有設置爲用戶未登錄,所以您得到了無級錯誤。