22

I'm using CanCan for authorization. I define the model-action-user rules in /app/config/ability.rb and it's working fine. I've added the line load_and_authorize_resource to my application_controller, and everything's done.

However, I also have numerous views and controllers that don't have a model underneath. For example, trying to load a statistics page gives

NameError (uninitialized constant Statistic):
  activesupport (3.2.3) lib/active_support/inflector/methods.rb:229:in `block in constantize'
  activesupport (3.2.3) lib/active_support/inflector/methods.rb:228:in `each'
  activesupport (3.2.3) lib/active_support/inflector/methods.rb:228:in `constantize'
  ...

Is there some way for CanCan to work with the controller+action instead of model+action?

4 Answers4

39

Use authorize_resource :class => false in your controller. CanCan will automatically check for abilities on the name of the controller (as a symbol, singular, eg :statistic for the StatisticsController)

See https://github.com/ryanb/cancan/wiki/Non-RESTful-Controllers

tight
  • 823
  • 6
  • 11
5

You can especify the controller within the ability.rb file:

ability.rb:

can :read, StatisticsController # ability.rb

StatisticsController:

class StatisticsController < ApplicationController

  def read
    authorize! :read, current_user 
  end
end
Community
  • 1
  • 1
bragamat
  • 101
  • 1
  • 3
2

None of the other answers worked for me but the following did:

can :read, :statistics # ability.rb

Then, in the controller you can either use

class StatisticsController < ApplicationController
  authorize_resource class: false
end

which will call authorize! :<action>, :statistics for you, or you can do it per action explicitly:

class StatisticsController < ApplicationController
  def index
    authorize! :read, :statistics
  end
end
PhilT
  • 4,166
  • 1
  • 36
  • 26
-1

you can use this gem cancacan "https://github.com/piedoom/cancancan" where the persons is finding update the gem cancan to the version of rails new

perrukozsh
  • 34
  • 1
  • 6