views:

50

answers:

3

It seems that those helpers in app/helpers/foo.rb can be used in View, but cannot be used in Controller?

In some cases, different controllers may need to use the same method but just pass in a different parameter, so in that case, won't it make sense to use a helper in a controller?

+1  A: 

It might make sense, but it doesn't work that way. (If anyone knows how to do that, feel free to post)

You can put common helpers in ApplicationController, they'll be accessible from any controller in your app.

Nikita Rybak
+3  A: 

There are two main ways to re-use code between controllers.

You can create a subclass of ApplicationController which has the common code in and then your controllers that want to share the code inherit from the new controller class. (Or just add the code to ApplicationController itself if it needs to be shared by all controllers.)

Alternatively you can create your own modules (this is all the helpers are in essence) and include them into the controllers that you want to use the code in.

As helpers are just modules you could include a helper in your controller but helpers are more for the view layer than the controller so it is rarely the place to share code between controllers.

Shadwell
+1  A: 

As mentioned above, you can put common helpers in ApplicationController or a subclass. I would add that to make them available to views as well, that you put at the top of the class:

helper_method :foo
Tim
Hi Lin, As Tim said you can put them in controller and define as helper methods Ex: ApplicationController < ActionController::Base helper_method :foo end
sameera207