简体   繁体   中英

Controller helper_method

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?

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.

to share methods between controller and view you have several options:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM