CanCan and controllers without models

user684934 picture user684934 · Jun 29, 2012 · Viewed 8.1k times · Source

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?

Answer

tight picture tight · Jun 29, 2012

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