helper和helper_method做什么? [英] What do helper and helper_method do?

查看:167
本文介绍了helper和helper_method做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

helper_method很简单:它使视图的某些或所有控制器方法可用.

helper_method is straightforward: it makes some or all of the controller's methods available to the view.

什么是helper?反过来,也就是将辅助方法导入文件或模块中吗? (也许名称helperhelper_method相似.相反,它们可能是share_methods_with_viewimport_methods_from_view)

What is helper? Is it the other way around, i.e., it imports helper methods into a file or a module? (Maybe the name helper and helper_method are alike. They may rather instead be share_methods_with_view and import_methods_from_view)

参考

推荐答案

方法helper_method用于显式共享控制器中定义的一些方法,以使其可用于视图.这用于需要从控制器和帮助器/视图访问的任何方法(控制器中不提供标准帮助器方法).例如常见用例:

The method helper_method is 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:

#application_controller.rb
def current_user
  @current_user ||= User.find_by_id!(session[:user_id])
end
helper_method :current_user

另一方面,

helper方法用于将整个助手导入到控制器(及其继承的控制器)提供的视图中.这意味着在做什么

the helper method 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

# application_controller.rb
helper :all

对于Rails> 3.1

For 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

使所有帮助程序模块可用于所有视图(至少适用于从application_controller继承的所有控制器.

makes all helper modules available to all views (at least for all controllers inheriting from application_controller.

# home_controller.rb
helper UserHelper

使UserHelper方法可用于家庭控制器操作的视图.这等效于:

makes the UserHelper methods available to views for actions of the home controller. This is equivalent to doing:

# HomeHelper
include UserHelper

这篇关于helper和helper_method做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆