Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 743
Evolutio Avatar asked Mar 22 '26 07:03

Evolutio


1 Answers

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
like image 83
bumpy Avatar answered Mar 24 '26 01:03

bumpy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!