gpt4 book ai didi

ruby-on-rails-4 - 基于未定义方法的模板错误 'custom_helper'

转载 作者:行者123 更新时间:2023-12-04 18:07:04 24 4
gpt4 key购买 nike

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

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

当我从其中一个 View 调用它时,出现错误:

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

但如果我按如下所示从 app/helpers/application_helper.rb 调用同一个助手,则 View 能够检测到助手。

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

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

config.action_controller.include_all_helpers = true

为什么不起作用?

最佳答案

默认情况下,助手中的方法只对它们对应的 Controller 可用。例如,PostsController 可以访问 PostsHelper 中的方法,但各种帖 subview 不能。如果您想让这些方法对 View 可用,请将它们指定为 helper_methods,如下所示:

module PostsHelper

helper_method :custom_helper

def custom_helper(post)
#do something
end
end

相比之下,ApplicationHelper 中定义的方法是全局可用的,即在所有 Controller 和 View 中。

您可以阅读提供的优秀答案 here了解更多详情。

您还可以在 ApplicationHelper 中包含一个模块,以使其方法具有全局可访问性:

module ApplicationHelper

include PostsHelper
...

end

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

关于ruby-on-rails-4 - 基于未定义方法的模板错误 'custom_helper',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23877164/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com