Using cancan to prevent access to controller

Ran picture Ran · Dec 25, 2010 · Viewed 10k times · Source

I have an admin controller and I want that only users that are defined as admin would have access to that controller.

my ability class:

class Ability
  include CanCan::Ability

  def initialize(user)
    if user.admin?
      can :manage, :all
    else
      can :read, :all
    end
  end
end

my admin controller:

class AdminController < ApplicationController
  load_and_authorize_resource

  def index
  end

  def users_list
  end
end

when i try to access /admin/users_list (either with an admin user or without) i get the following error: uninitialized constant Admin

What am I doing wrong? Is that the right way to restrict access to a controller?

Answer

Lars Tackmann picture Lars Tackmann · Dec 31, 2010

This is because when you are using load_and_authorize_resource your controller must be backed by a model named Admin (since your controller is called AdminController). Thus you need to either create this model or replace load_and_authorize_resource with:

authorize_resource :class => false

which causes the access checks to be made against your actions rather than the model. Note this unfortunately causes the generic access symbols such as :manage and :read to stop working requiring you to refernce the controller actions directly in ability.rb:

can [ :index, :users_list ], :admin

where the first argument is a array of controller actions the user can access and the second argument is the short name of the controller