Controller helper_method

后端 未结 2 1005
故里飘歌
故里飘歌 2020-12-23 16:40

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.

相关标签:
2条回答
  • 2020-12-23 16:56

    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.

    0 讨论(0)
  • 2020-12-23 17:15

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

    • use view_context http://apidock.com/rails/AbstractController/Rendering/view_context
    • define it in the controller and make available in view by the helper_method class method http://apidock.com/rails/ActionController/Helpers/ClassMethods/helper_method
    • define it in a shared module and include/extend
    0 讨论(0)
提交回复
热议问题