Rails: 多个控制器共享的方法

Rails: Methods shared by multiple controllers

我有两个控制器,即 1) carts_controller 2) orders_controller

class CartsController < ApplicationController
  helper_method :method3

  def method1
  end

  def method2
  end

  def method3
    # using method1 and method2
  end
end

注意:method3 正在使用 method1method2CartsControllershowcart.html.erb 视图,它正在使用 method3 并且工作正常。

现在在订单视图中,我需要显示购物车 (showcart.html.erb),但由于 method3 是在 carts_controller 中定义的,所以它无法访问它。

如何解决?

因为您正在使用 Rails 4(这种方法应该也适用于 Rails 的较新版本),在您的控制器之间共享代码的推荐方法是使用 Controller Concerns。控制器关注点是可以混合到控制器中以在它们之间共享代码的模块。因此,您应该将常用的辅助方法放在控制器关注点中,并将关注点模块包含在您需要使用辅助方法的所有控制器中。

在你的情况下,因为你想在两个控制器之间共享 method3,你应该关注它。请参阅 this tutorial 了解如何引起关注并在控制者之间分享 codes/methods。

这里有一些代码可以帮助您开始:

定义您的控制器关注点:

# app/controllers/concerns/your_controller_concern.rb
module YourControllerConcern
  extend ActiveSupport::Concern

  included do
    helper_method :method3
  end

  def method3
    # method code here
  end
end

然后,将问题包含在您的控制器中:

class CartsController < ApplicationController
  include YourControllerConcern
  # rest of the controller codes
end

class OrdersController < ApplicationController
  include YourControllerConcern
  # rest of the controller codes
end

现在,您应该可以在两个控制器中使用 method3