I was wondering why someone should use helper_method inside a controller to create a helper method, instead of creating the "normal" way, which is inside the helper file. What the pros and cons of that?
The method helper_method is to explicitly share some methods defined in the controller to make them available for the view. This is used for any method that you need to access from both controllers and helpers/views (standard helper methods are not available in controllers).
A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words .
A helper method is a small utility function that can be used to extract logic from views and controllers, keeping them lean. Views should never have logic because they're meant to display HTML.
A helper method is just a method that helps you do something else. For example, if you had to find the square root of a number multiple times within a method, you wouldn't write out the code to find the root each time you needed it, you'd separate it out into a method like Math.
helper_method
is useful when the functionality is something that's used between both the controller and the view. A good example is something like current_user
.
If the method deals more with controller logic and not formatting then it belongs in the controller. Something like current_user
would be shared between all controllers so it should be defined in the ApplicationController
.
True "helper" methods deal with the view and handle things like formatting and template logic. These are seldom needed in the controller and they belong in their own module under app/helpers. You can include these in your controller when needed, but you end up with the whole module worth of view helper methods available to your controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With