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

时间:2015-11-12 01:03:18

标签: ruby-on-rails ruby ruby-on-rails-4

我有两个控制器,即 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,因此无法访问它。

如何解决?

2 个答案:

答案 0 :(得分:30)

当您使用Rails 4时,在控制器之间共享代码的推荐方法是使用Controller Concerns。 Controller Concerns是可以混合到控制器中以在它们之间共享代码的模块。因此,您应该将常见的帮助器方法放在控制器中,并在所有需要使用辅助方法的控制器中包含关注模块。

在您的情况下,由于您希望在两个控制器之间共享method3,因此您应该将其置于关注之中。请参阅this tutorial以了解如何在控制器之间创建关注点和共享代码/方法。

以下是一些可帮助您实现目标的代码:

定义控制器问题:

# 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

答案 1 :(得分:0)

您无法使用其他控制器中的方法,因为它未在当前请求中实例化。

将所有三个方法移动到两个控制器(或ApplicationController)的父类,或者移动到帮助器,以便它们都可以访问