【问题标题】:authorise view user to not access some pages in rails4 app by using cancancan使用 cancancan 授权查看用户不访问 rails4 应用程序中的某些页面
【发布时间】:2014-11-22 07:41:26
【问题描述】:

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

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

【问题讨论】:

  • 你能告诉我你在哪里定义你的当前用户吗?或者您使用的是哪种型号?
  • 我在dashboard_user.rb模型@Rubyrider中使用设计
  • 好的,所以问题出在某个地方,您正在使用 current_user!你能先找到那个方块吗?
  • 我只使用 current_dashboard_user。在给 load_and_authorize_resource 之后,只会出现这个错误
  • 我在回答中做了更新。 helper_method: :current_user

标签: ruby-on-rails ruby devise cancan cancancan


【解决方案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

我希望这会有所帮助。

【讨论】:

  • 谢谢。它解决了但是。现在它显示错误未定义方法“CD_DASHBOARD_ADMIN?”对于#<0x007fa019ab4170>
  • <0x007fa019ab4170>
猜你喜欢
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
  • 1970-01-01
  • 2017-12-25
  • 2015-09-14
  • 1970-01-01
相关资源
最近更新 更多