如何在模块中使用'before_action'

flp*_*flp 28 gem module ruby-on-rails

我想在模块中使用'before_action'.

不幸的是,我无法让它发挥作用.

我是googleing,但我发现的一切都无法解决问题.

我的模块文件如下所示:

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

  def show
   set_object
  end
end
Run Code Online (Sandbox Code Playgroud)

我想使用outcommented before_action行而不是show方法.

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

  include AbstractController::Callbacks
  include ActiveSupport::Callbacks
  include ActiveSupport::Concern
  include ActiveSupport
Run Code Online (Sandbox Code Playgroud)

另外,我试图"要求'active_support/all'"或core_ext.

我收到的error_message是:

 undefined method `class_attribute' for SimpleController::ShowController:Module
Run Code Online (Sandbox Code Playgroud)

最后,没有任何结果,我没有找到解决方案.

eva*_*kes 43

我想这就是你要做的事情:

class SomeController < ActionController::Base
  include SimpleController
end 

module SimpleController
  extend ActiveSupport::Concern

  included do
    before_action :set_object, only: [:show]
  end
end
Run Code Online (Sandbox Code Playgroud)