控制器 helper_method [英] Controller helper_method
问题描述
我想知道为什么有人应该在控制器中使用 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
在控制器和视图之间同时使用功能时很有用.一个很好的例子是类似 current_user
的东西.
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
.
如果该方法更多地处理控制器逻辑而不是格式化,那么它属于控制器.像 current_user
这样的东西会在所有控制器之间共享,所以它应该在 ApplicationController
中定义.
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
.
真正的助手"方法处理视图并处理格式和模板逻辑之类的事情.这些在控制器中很少需要,它们属于 app/helpers 下自己的模块.您可以在需要时将这些包含在您的控制器中,但最终您会得到整个模块中值得您的控制器使用的视图助手方法.
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.
这篇关于控制器 helper_method的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!