cancancan load_and_authorize_resource NameError

时间:2015-08-23 13:35:13

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

我使用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

1 个答案:

答案 0 :(得分:6)

您可以使用CanCanCan而不使用authorize_resource :class => false这样的相应模型

class PanelController < ApplicationController
  authorize_resource :class => false

  def dashboard
  end
end

然后以你的能力:

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