简体   繁体   中英

How to use 'before_action' in a module

I would like to use 'before_action' in a module.

Unfortunately, I couldn't get it work.

I was googleing, but everything I found couldn't solve the problem.

My module file looks like the following:

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

  def show
   set_object
  end
end

I would like to use the outcommented before_action line instead of the show method.

Therefore, I was trying to include the following modules:

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

Additionally, I tried to "require 'active_support/all'" or the core_ext.

The error_message I receive is:

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

Finally, nothing worked out and I didn't find a solution.

I think this is what you're trying to do:

class SomeController < ActionController::Base
  include SimpleController
end 

module SimpleController
  extend ActiveSupport::Concern

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM