问题
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?
回答1:
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
回答2:
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
回答3:
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
来源:https://stackoverflow.com/questions/11256969/cancan-and-controllers-without-models