Evolutio
Evolutio

Reputation: 974

cancancan load_and_authorize_resource NameError

I use the CanCanCan, Devise and Rolify gem to for authentication and permission management. But when I create a new controller I got this message:

NameError in PanelController#dashboard
uninitialized constant Panel

My PanelController:

class PanelController < ApplicationController
  load_and_authorize_resource

  def dashboard
  end
end

When I remove this line: load_and_authorize_resource the Route works. But I can access it without authentication. Do I need a PanelModel to use it?

My AbilityModel is this:

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

Yesterday my Code works great but today I don't know why I get this error. Maybe anyone can help me.

My Routes are this for the Controller:

  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

Upvotes: 3

Views: 1894

Answers (1)

bumpy
bumpy

Reputation: 2002

You can use CanCanCan without a corresponding model using authorize_resource :class => false like this

class PanelController < ApplicationController
  authorize_resource :class => false

  def dashboard
  end
end

and then in your ability:

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

Upvotes: 7

Related Questions