我有两个 Controller ,即 1)carts_controller 2) 订单 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
View ,它使用 method3 并且工作正常。
现在在订单 View 中,我需要显示购物车 (showcart.html.erb
),但由于辅助程序 method3
是在 carts_controller
中定义的所以它无法访问它。
如何解决?
最佳答案
由于您使用的是 Rails 4(这种方法应该也适用于较新版本的 Rails),因此在 Controller 之间共享代码的推荐方法是使用 Controller Concerns。 Controller 关注点是可以混合到 Controller 中以在它们之间共享代码的模块。因此,您应该将常用的辅助方法放在 Controller 关注点中,并在需要使用辅助方法的所有 Controller 中包含关注点模块。
在你的情况下,因为你想在两个 Controller 之间共享 method3
,你应该关注它。参见 this tutorial了解如何在 Controller 之间创建关注点和共享代码/方法。
这里有一些代码可以帮助您开始:
定义 Controller 关注点:
# 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
然后,将问题包含在您的 Controller 中:
class CartsController < ApplicationController
include YourControllerConcern
# rest of the controller codes
end
class OrdersController < ApplicationController
include YourControllerConcern
# rest of the controller codes
end
现在,您应该能够在两个 Controller 中使用method3
。
关于ruby-on-rails - rails : Methods shared by multiple controllers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33662740/