Rails:多个控制器共享的方法 [英] Rails: Methods shared by multiple controllers

查看:27
本文介绍了Rails:多个控制器共享的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个控制器,即1)carts_controller2) 订单控制器

I have two controllers, i.e 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 使用的是 method1method2.CartsControllershowcart.html.erb 视图,它使用 method3 并且工作正常.

Note: method3 is using method1 and method2. CartsController has showcart.html.erb view which is using method3 and works fine.

现在在 order 的视图中,我需要显示购物车 (showcart.html.erb) 但作为帮助器 method3carts_controller 中定义所以它无法访问它.

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.

如何解决?

推荐答案

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

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. 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.

在您的情况下,由于您想在两个控制器之间共享 method3,您应该关注它.请参阅本教程,了解如何创建关注点和在控制器之间共享代码/方法.

In your case, as you want to share method3 between two controllers, you should put it in a concern. See this tutorial to know how to create concern and share codes/methods among controllers.

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

Here are some codes to help you get going:

定义控制器关注点:

# 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

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

Now, you should be able to use method3 in both controllers.

这篇关于Rails:多个控制器共享的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆