Rails4: Methods Used by Multiple Controllers

I have two controllers, i.e. 1) carts_controller 2) order_controller

class CartsController < ApplicationController helper_method :method3 def method1 end def method2 end def method3 # using method1 and method2 end end 

Note: method3 uses method1 and method2 . CartsController has the form showcart.html.erb , which uses method3 and works fine.

Now in view mode, I need to display the cart ( showcart.html.erb ), but since the method3 helper method3 defined in carts_controller , so it cannot access it.

How to fix it?

+6
source share
2 answers

Since you are using Rails 4, the recommended way to share code between your controllers is to use the Controller Concern. Controller concerns are modules that can be mixed with controllers to share code between them. Therefore, you must include the common helper methods in the controller and include the anxiety module in all your controllers where you need to use the helper method.

In your case, since you want to share method3 between two controllers, you have to worry about it. See this tutorial to learn how to create problems and share codes / methods among controllers.

Here are some codes to help you jump:

Identify the problem with the 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 

Then include care 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 can use method3 in both controllers.

+20
source

You cannot use methods from another controller because it is not created in the current request.

Move all three methods to the parent class of both controllers (or ApplicationController) or to the helper so that they are accessible as for

0
source

All Articles