【问题标题】:How to link controllers in Ruby On Rails? [duplicate]如何在 Ruby On Rails 中链接控制器? [复制]
【发布时间】:2017-04-08 19:22:36
【问题描述】:

有时我需要一个控制器来使用另一个控制器的操作。我现在做的是实例化它并使用它的操作,但它给我的感觉是我所做的不正确,所以我被教导不能有同一个控制器的多个实例。

最佳做法是什么?非常感谢。

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案1】:

这就是您链接控制器的方式 制作方法.self

class TestController < ApplicationController
  def self.get_details(data)
  end
end 

然后:

class ChildrenController < ApplicationController
  def set_details        
    TestController.get_details(data)
  end
end

创建库模块的其他选项

lib/common_stuff.rb

module CommonStuff
  def common_thing
    # code
  end
end

app/controllers/my_controller.rb

require 'common_stuff'
class MyController < ApplicationController
  include CommonStuff
  # has access to common_thing
end

【讨论】:

    【解决方案2】:

    Rails 中的良好做法是将通用逻辑移至 service/module/lib/gem。如果您需要的操作仅特定于控制器,那么您定义抽象控制器并从中继承您的控制器。就像你对ApplicationController 所做的那样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多