2014-11-22 35 views
1

我正在使用Devise進行身份驗證,並且cancancan進行授權。現在,我希望不允許某些頁面的視圖用戶。所以我添加下面的代碼。但是它會爲#錯誤拋出未定義的局部變量或方法`current_user'。授權查看用戶不使用cancancan訪問rails4應用程序中的某些頁面

我ability.rb

class Ability 
    include CanCan::Ability 

    def initialize(dashboard_user) 

     current_dashboard_user ||= DashboardUser.new 
     if current_dashboard_user.CD_DASHBOARD_ADMIN? 
     can :manage, :all 
     else 
     can :read, :summary 
     can :read, :home 
     end 
     ......... 
    end 

Application_controller.rb

class ApplicationController < ActionController::Base 

    protect_from_forgery with: :exception 
    before_action :configure_permitted_parameters, if: :devise_controller? 

    before_action :authenticate_dashboard_user! 

    protected 
    rescue_from CanCan::AccessDenied do |exception| 
    redirect_to main_app.root_url, :alert => exception.message 
    end 
    .... 
end 

dashboard_user_controller.rb

class DashboardUsersController < ApplicationController 
    before_action :set_dashboard_user, only: [:show, :edit, :update, :destroy] 

    load_and_authorize_resource 
    .... 
end 
+0

你能告訴我你在哪裏定義你的當前用戶嗎?或者你正在使用哪種模型設計? – Rubyrider 2014-11-22 07:42:51

+0

上午在dashboard_user.rb模型中使用devise @Rubyrider – 2014-11-22 07:45:11

+0

okey,所以問題在某處,您正在使用current_user!你能先找到那個塊嗎? – Rubyrider 2014-11-22 07:45:57

回答

1

歐凱,只是做這一招現在。以某種方式調用current_user輔助方法。所以最快的解決方案是,如果你可以做到以下幾點。

在你application_controller.rb文件中把這個塊:

def current_user 
    current_dashboard_user 
    end 

    # method_alias :current_user=, current_user # you may need this line if required. 
    helper_method: :current_user 

我希望這將有助於。

+0

謝謝。它解決了但。現在它顯示錯誤未定義的方法'CD_DASHBOARD_ADMIN?'爲# 2014-11-22 07:55:38

+0

這是不同的問題兄弟。我們需要通過你的模型,爲什麼它會給你錯誤。 – Rubyrider 2014-11-22 07:56:17

+0

我的答案是否解決了有關current_user的特定問題? – Rubyrider 2014-11-22 07:56:42

相關問題