Ruby-on-rails helper 和 helper_method 做什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3992659/
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
What do helper and helper_method do?
提问by nonopolarity
helper_methodis straightforward: it makes some or all of the controller's methods available to the view.
helper_method很简单:它使控制器的部分或全部方法可用于视图。
What is helper? Is it the other way around, i.e., it imports helper methods into a file or a module? (Maybe the name helperand helper_methodare alike. They may rather instead be share_methods_with_viewand import_methods_from_view)
什么是helper?是不是反过来,即将辅助方法导入文件或模块?(也许名字helper和helper_method是相似的。他们可能宁愿是share_methods_with_view和import_methods_from_view)
回答by Jeremy
The method helper_methodis 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). e.g. common use case:
该方法helper_method是显式共享控制器中定义的一些方法,使它们可用于视图。这用于您需要从控制器和助手/视图访问的任何方法(标准助手方法在控制器中不可用)。例如常见用例:
#application_controller.rb
def current_user
@current_user ||= User.find_by_id!(session[:user_id])
end
helper_method :current_user
the helpermethod on the other hand, is for importing an entire helper to the views provided by the controller (and it's inherited controllers). What this means is doing
helper另一方面,该方法用于将整个帮助程序导入控制器提供的视图(并且它是继承的控制器)。这意味着正在做什么
# application_controller.rb
helper :all
For Rails > 3.1
对于 Rails > 3.1
# application.rb
config.action_controller.include_all_helpers = true
# This is the default anyway, but worth knowing how to turn it off
makes all helper modules available to all views (at least for all controllers inheriting from application_controller.
使所有辅助模块可用于所有视图(至少对于从 application_controller 继承的所有控制器。
# home_controller.rb
helper UserHelper
makes the UserHelper methods available to views for actions of the home controller. This is equivalent to doing:
使 UserHelper 方法可用于主控制器操作的视图。这相当于做:
# HomeHelper
include UserHelper

