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

Kho*_*oga 8 ruby ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)

注意:method3正在使用method1method2. CartsControllershowcart.html.erb视图使用method3并且工作正常.

现在在顺序视图中,我需要显示cart(showcart.html.erb)但是由于method3定义了帮助程序carts_controller所以它无法访问它.

怎么解决?

K M*_*lam 33

当您使用Rails 4时,在控制器之间共享代码的推荐方法是使用Controller Concerns.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
Run Code Online (Sandbox Code Playgroud)

然后,在控制器中包含关注点:

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

class OrdersController < ApplicationController
  include YourControllerConcern
  # rest of the controller codes
end
Run Code Online (Sandbox Code Playgroud)

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