Rails4:多个控制器共享的方法
我有两个控制器,即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
使用method1
和method2
。 CartsController
有showcart.html.erb
视图,它使用method3并且工作正常。
现在按顺序查看,我需要显示购物车( showcart.html.erb
),但是因为帮助方法method3
在carts_controller
定义所以它无法访问它。
怎么解决?
在使用Rails 4时,在控制器之间共享代码的推荐方法是使用Controller Concerns。 控制器问题是可以混合到控制器中以在它们之间共享代码的模块。 因此,您应该将常见的帮助器方法放在控制器中,并在所有需要使用辅助方法的控制器中包含关注模块。
在你的情况下,因为你想在两个控制器之间共享method3
,你应该把它放在一个问题中。 请参阅本教程 ,了解如何在控制器之间创建关注点和共享代码/方法。
以下是一些可帮助您开展的代码:
定义控制器问题:
# 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
。
您不能使用其他控制器中的方法,因为它未在当前请求中实例化。
将所有三个方法移动到两个控制器(或ApplicationController)的父类,或者移动到帮助程序,以便它们都可以访问