简体   繁体   中英

Including rails controller action in concern

Is it possible to add a controller action via a concern?

I am trying to include a controller action via concern but it is not getting found:

module Wizbang
  module ActsAsWizbang
    extend ActiveSupport::Concern

    included do

      def foo
        # do something
      end
    end
end

I've added the approprioate route to my routes file, but it can't find the action on the controller.

When I include this code in my controller

class SimpleController < ApplicationController

  include Wizbang::ActsAsWizbang

end

I receive the message:

The action 'foo' could not be found for SimpleController.

If you want to define methods to mix into the class, just define them in the module. They don't go inside an included block:

module Wizbang
  module ActsAsWizbang
    extend ActiveSupport::Concern

    def foo
      # do something
    end
  end
end

Double check that your include statement resolves correctly.

I got down this rabbit hole recently, but my problem wasn't that I was doing the concern wrong - it was because the include statement that I was using was not correct, but that error was somehow swallowed and I saw this instead. I ended up with something like the following, but your case may vary.

module Api::V1::Concerns
  module Foo
    extend ActiveSupport::Concerns
...


module Api::V1::Bar
  class BazController < ActionController::API
    include Api::V1::Concerns::Foo

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