CanCan和控制器没有型号

14 ruby-on-rails cancan

我正在使用CanCan进行授权.我在/app/config/ability.rb中定义了模型 - 操作 - 用户规则,它运行正常.我已将该行添加load_and_authorize_resource到我的application_controller中,一切都已完成.

但是,我还有许多视图和控制器,下面没有模型.例如,尝试加载统计页面给出

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'
  ...
Run Code Online (Sandbox Code Playgroud)

有没有办法让CanCan能够使用控制器+动作而不是模型+动作?

tig*_*ght 27

authorize_resource :class => false在控制器中使用.惨惨会自动检查在控制器的名称能力(为标志,单数,例如:statisticStatisticsController)

请参阅https://github.com/ryanb/cancan/wiki/Non-RESTful-Controllers

  • @MadhanAyyasamy我不这么认为 (3认同)

小智 5

您可以在文件中指定控制器ability.rb

能力.rb:

can :read, StatisticsController # ability.rb
Run Code Online (Sandbox Code Playgroud)

统计控制器:

class StatisticsController < ApplicationController

  def read
    authorize! :read, current_user 
  end
end
Run Code Online (Sandbox Code Playgroud)