Ruby-on-rails 控制器 helper_method

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3549713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:05:50  来源:igfitidea点击:

Controller helper_method

ruby-on-railsruby-on-rails-3

提问by JohnDel

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 来创建辅助方法,而不是创建辅助文件中的“正常”方式。这样做有什么好处和坏处?

回答by Andrew Vit

helper_methodis useful when the functionality is something that's used between both the controller and the view. A good example is something like current_user.

helper_method当功能在控制器和视图之间使用时很有用。一个很好的例子是类似current_user.

If the method deals more with controller logic and not formatting then it belongs in the controller. Something like current_userwould be shared between all controllers so it should be defined in the ApplicationController.

如果该方法更多地处理控制器逻辑而不是格式化,那么它属于控制器。类似的东西current_user会在所有控制器之间共享,所以它应该在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.

真正的“助手”方法处理视图并处理格式和模板逻辑之类的事情。这些在控制器中很少需要,它们属于 app/helpers 下自己的模块。您可以在需要时将这些包含在您的控制器中,但最终您会得到整个模块值得的视图助手方法可用于您的控制器。

回答by Viktor Trón

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

要在控制器和视图之间共享方法,您有多种选择: