cancancan load_and_authorize_resource NameError

3
我使用 CanCanCan、Devise 和 Rolify gem 进行身份验证和权限管理。但是当我创建一个新的控制器时,会得到以下提示信息:
NameError in PanelController#dashboard
uninitialized constant Panel

我的PanelController:

class PanelController < ApplicationController
  load_and_authorize_resource

  def dashboard
  end
end

当我移除这行代码:load_and_authorize_resource时,路由可以正常工作。但是我可以在未经过身份验证的情况下访问它。我需要一个PanelModel来使用它吗?

我的AbilityModel是这样的:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)

    alias_action :create, :read, :update, :destroy, :to => :crud

    if user.has_role? :admin
      can :manage, :all
    elsif user.has_role? :user
      can [:read], User
      can [:update, :edit], User do |account|
        account.email == user.email
      end
    else
      # can :read, :all
      can [:create, :new], User
    end
  end
end

昨天我的代码运行得很好,但今天我不知道为什么会出现这个错误。也许有人可以帮我。

我的控制器路由如下:

  devise_scope :user do
    authenticated :user do
      # Rails 4 users must specify the 'as' option to give it a unique name
      root :to => "panels#dashboard", :as => :panel
    end

    unauthenticated do
      root 'devise/sessions#new', as: :unauthenticated_root
    end
  end

是的,load_and_authorize_resource 正在寻找 Panel 模型。 - bumpy
但是为什么呢?我如何在进行身份验证的情况下使用它而不尝试查找PanelModel? - Evolutio
你将如何在没有Panel模型的情况下,在Ability类中检查仪表板操作的权限? - bumpy
我可以通过routes.rb文件来检查吗? - Evolutio
你可以这样做,但是为什么还需要使用 CanCanCan 进行另一个检查呢? - bumpy
我不确定。我在想通过使用 load_and_authorize_resource,我可以检查用户是否有权查看此页面,而无需使用模型。 - Evolutio
1个回答

7
您可以使用authorize_resource :class => false来使用CanCanCan而无需相应的模型,如下所示。
class PanelController < ApplicationController
  authorize_resource :class => false

  def dashboard
  end
end

然后在你的能力范围内:

elsif user.has_role? :user
  can :dashboard, :panel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接