【问题标题】:How to use 'before_action' in a module如何在模块中使用“before_action”
【发布时间】:2015-03-08 03:52:20
【问题描述】:

我想在模块中使用“before_action”。

很遗憾,我无法让它工作。

我在谷歌上搜索,但我发现的一切都无法解决问题。

我的模块文件如下所示:

module ShowController
  include SimpleController
  #before_action :set_object, only: [:show]

  def show
   set_object
  end
end

我想使用注释掉的 before_action 行而不是 show 方法。

因此,我试图包含以下模块:

  include AbstractController::Callbacks
  include ActiveSupport::Callbacks
  include ActiveSupport::Concern
  include ActiveSupport

此外,我尝试“要求'active_support/all'”或core_ext。

我收到的error_message是:

 undefined method `class_attribute' for SimpleController::ShowController:Module

最后,什么都没解决,我也没有找到解决办法。

【问题讨论】:

  • 如果您收到undefined method 'class_attribute',您可能需要将 ShowController 设为类而不是模块。

标签: ruby-on-rails module gem


【解决方案1】:

我认为这就是你想要做的:

class SomeController < ActionController::Base
  include SimpleController
end 

module SimpleController
  extend ActiveSupport::Concern

  included do
    before_action :set_object, only: [:show]
  end
end

【讨论】:

  • 我的示例是用于控制器,而不是模型。如果您在模型中使用它,那么您可以使用 ActiveRecord 回调,例如 before_commit 或 after_save 等。
  • 抱歉,我解释得有点糟糕——我实际上是在控制器关注点中这样做的,但我现在发现我不小心将控制器关注点命名为与我的其他模型关注点相同的名称,这给了我错误:P 我的不好。
  • 但是如果我然后运行 ​​before_action :set_object,只有: SomeController 中的 [:something] 这会覆盖之前的 before_action 吗?据说,如果这是完全继承,则不会,但包含的 do 只是执行类中的结果代码,所以稍后 before_actions do...??
猜你喜欢
  • 2017-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多