1

我使用 Devise 进行身份验证,使用 cancancan 进行授权。现在我不想让查看用户访问某些页面。所以我添加了以下代码。但它会为 # 错误抛出未定义的局部变量或方法 `current_user'。

我的能力.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

仪表板_用户_控制器.rb

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

  load_and_authorize_resource
  ....
end
4

1 回答 1

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

我希望这将有所帮助。

于 2014-11-22T07:52:55.430 回答