简体   繁体   English

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

[英]Rails: Methods shared by multiple controllers

I have two controllers, ie 1) carts_controller 2) orders_controller我有两个控制器,即 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

Note: method3 is using method1 and method2 .注意: method3正在使用method1method2 CartsController has showcart.html.erb view which is using method3 and works fine. CartsControllershowcart.html.erb视图,它使用 method3 并且工作正常。

Now in order's view, I need to display cart ( showcart.html.erb ) but as the helper method3 is defined in carts_controller so it cannot access it.现在在订单视图中,我需要显示购物车( showcart.html.erb ),但由于辅助方法method3是在carts_controller定义的,因此它无法访问它。

How to fix it ?如何解决?

As you are using Rails 4 (This approach should work in newer versions of Rails as well), the recommended way of sharing code among your controllers is to use Controller Concerns.由于您使用的是 Rails 4(这种方法也适用于较新版本的 Rails),推荐的在控制器之间共享代码的方法是使用 Controller Concerns。 Controller Concerns are modules that can be mixed into controllers to share code between them.控制器关注点是可以混合到控制器中以在它们之间共享代码的模块。 So, you should put the common helper methods inside the controller concern and include the concern module in all of your controllers where you need to use the helper method.因此,您应该将常见的辅助方法放在控制器关注中,并将关注模块包含在您需要使用辅助方法的所有控制器中。

In your case, as you want to share method3 between two controllers, you should put it in a concern.在您的情况下,由于您想在两个控制器之间共享method3 ,您应该关注它。 See this tutorial to know how to create concern and share codes/methods among controllers.请参阅本教程以了解如何在控制器之间创建关注和共享代码/方法。

Here are some codes to help you get going:这里有一些代码可以帮助你开始:

Define you controller concern:定义您的控制器关注点:

# 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

Then, include the concern in your controllers:然后,在您的控制器中包含关注点:

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

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

Now, you should be able to use method3 in both controllers.现在,您应该能够在两个控制器中使用method3

You cannot use methods from other controller, because it's not instantiated in current request. 您不能使用其他控制器中的方法,因为它未在当前请求中实例化。

Move all three methods to parent class of both controllers (or ApplicationController), or to a helper, so they will be accessible to both 将所有三个方法移动到两个控制器(或ApplicationController)的父类,或者移动到帮助程序,以便它们都可以访问

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM