基于未定义方法的模板错误' custom_helper'

时间:2014-05-26 20:18:19

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

我在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

为什么它不起作用?

1 个答案:

答案 0 :(得分:0)

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

module PostsHelper

  helper_method :custom_helper

  def custom_helper(post)
    #do something
 end
end

相比之下,ApplicationHelper中定义的方法可在全球范围内使用,即在所有控制器和视图中使用。

您可以阅读here提供的优秀答案以获取更多详细信息。

您还可以include ApplicationHelper中的模块为其方法提供全局可访问性:

module ApplicationHelper

  include PostsHelper
  ...

end

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