ruby-on-railscancan

CanCan and controllers without models


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?


Solution

  • 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