18

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

4 回答 4

34

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

于 2012-06-29T09:57:19.660 回答
4

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
于 2019-05-28T17:09:34.733 回答
0

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
于 2021-10-26T19:59:45.313 回答
-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

于 2018-01-13T13:41:33.647 回答