nonopolarity
nonopolarity

Reputation: 151036

In Rails, any way to use app/helpers/foo.rb methods in Controller vs in View?

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?

Upvotes: 3

Views: 274

Answers (3)

coder_tim
coder_tim

Reputation: 1720

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

Upvotes: 1

Shadwell
Shadwell

Reputation: 34774

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.

Upvotes: 3

Nikita Rybak
Nikita Rybak

Reputation: 68006

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.

Upvotes: 1

Related Questions