简体   繁体   English

包括轨道控制器动作

[英]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. 我已将approprioate路由添加到我的路由文件中,但它无法在控制器上找到该操作。

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: 它们不会进入included块内:

module Wizbang
  module ActsAsWizbang
    extend ActiveSupport::Concern

    def foo
      # do something
    end
  end
end

Double check that your include statement resolves correctly. 仔细检查include语句是否正确解析。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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