【问题标题】:CanCan and controllers without modelsCanCan 和没有模型的控制器
【发布时间】:2012-06-29 06:19:17
【问题描述】:

我正在使用 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'
  ...

CanCan 有什么方法可以使用控制器+动作而不是模型+动作吗?

【问题讨论】:

    标签: ruby-on-rails cancan


    【解决方案1】:

    在您的控制器中使用authorize_resource :class => false。 CanCan 将自动检查控制器名称上的能力(作为符号,单数,例如:statistic 代表StatisticsController

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

    【讨论】:

    • 如果你使用的是load_and_authorize_resource方法,就不用提class=> false.cancan会默认检查找出来。
    • @MadhanAyyasamy 我不这么认为
    • @MadhanAyyasamy load_and_authorize_resource 如果您不告诉它该控制器没有模型,则会中断...
    • 谢谢你。在他们的文档中找不到任何提到在能力.rb 中将控制器作为单数符号传递的内容。
    • 对我不起作用。也许是因为我的控制器已经是单一的(家)。
    【解决方案2】:

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

    ability.rb:

    can :read, StatisticsController # ability.rb
    

    统计控制器:

    class StatisticsController < ApplicationController
    
      def read
        authorize! :read, current_user 
      end
    end
    

    【讨论】:

      【解决方案3】:

      没有其他答案对我有用,但以下答案对我有用:

      can :read, :statistics # ability.rb
      

      然后,您可以在控制器中使用

      class StatisticsController < ApplicationController
        authorize_resource class: false
      end
      

      它将为您调用authorize! :&lt;action&gt;, :statistics,或者您可以明确地为每个操作执行此操作:

      class StatisticsController < ApplicationController
        def index
          authorize! :read, :statistics
        end
      end
      

      【讨论】:

        【解决方案4】:

        你可以使用这个 gem cancacan "https://github.com/piedoom/cancancan" 来更新 gem cancan 到 rails new 的版本

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-08-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多