Doug
Doug

Reputation: 15553

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.

Upvotes: 6

Views: 2799

Answers (2)

Adverbly
Adverbly

Reputation: 2159

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

Upvotes: 0

user229044
user229044

Reputation: 239541

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

Upvotes: 2

Related Questions