【问题标题】:Template error based on undefined method 'custom_helper'基于未定义方法“custom_helper”的模板错误
【发布时间】:2014-07-15 15:25:44
【问题描述】:

我在app/helpers/posts_helpers.rb 中有一个自定义助手:

module PostsHelper
  def custom_helper(post)
    #do something
  end
end

当我从一个视图调用它时,我得到了错误:

ActionView::Template::Error (undefined method 'custom_helper' for class..

但如果我从app/helpers/application_helper.rb 调用相同的助手如下,那么视图能够检测到助手。

module ApplicationHelper
  def custom_helper(post)
    #do something
  end
end

即使在config/application.rb 中默认设置为 true,甚至尝试将 include all helper 选项显式设置为 true。这也没有帮助。

config.action_controller.include_all_helpers = true

为什么没用?

【问题讨论】:

    标签: ruby-on-rails-4 view-helpers


    【解决方案1】:

    默认情况下,帮助器中的方法仅对其对应的控制器可用。例如,PostsController 可以访问PostsHelper 中的方法,但各种帖子视图却没有。如果您想让这些方法对视图可用,请将它们指定为 helper_methods,如下所示:

    module PostsHelper
    
      helper_method :custom_helper
    
      def custom_helper(post)
        #do something
     end
    end
    

    相比之下,ApplicationHelper 中定义的方法是全局可用的,即在所有控制器和视图中。

    您可以阅读here 提供的出色答案以了解更多详细信息。

    您也可以在 ApplicationHelper 中include 一个模块,为其方法提供全局可访问性:

    module ApplicationHelper
    
      include PostsHelper
      ...
    
    end
    

    但这并不总是一个好主意,因为它会使您的代码难以理解和以后维护。

    【讨论】:

    • 感谢您的回复。 helper_method 用于控制器下的方法。我在这里问的是,来自 app/helpers/ 文件夹。默认情况下,这些对控制器不可用,但对视图可用。
    猜你喜欢
    • 1970-01-01
    • 2010-11-09
    • 2012-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    相关资源
    最近更新 更多