Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
802 views
in Technique[技术] by (71.8m points)

ruby - Rails: Methods shared by multiple controllers

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

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

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.

How to fix it ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...