gpt4 book ai didi

ruby-on-rails - Rails - 如何在 Controller 内使用助手

转载 作者:行者123 更新时间:2023-12-03 04:10:39 25 4
gpt4 key购买 nike

虽然我意识到您应该在 View 中使用助手,但我在 Controller 中需要一个助手,因为我正在构建要返回的 JSON 对象。

它有点像这样:

def xxxxx

@comments = Array.new

@c_comments.each do |comment|
@comments << {
:id => comment.id,
:content => html_format(comment.content)
}
end

render :json => @comments
end

如何访问我的 html_format 帮助程序?

最佳答案

您可以使用

  • helpers.<helper>Rails 5+(或 ActionController::Base.helpers.<helper> )
  • view_context.<helper> (Rails 4 和 3)(警告:每次调用都会实例化一个新的 View 实例)
  • @template.<helper> (Rails 2)
  • 在单例类中包含助手,然后 singleton.helper
  • include Controller 中的帮助器(警告:将使所有帮助器方法进入 Controller 操作)

关于ruby-on-rails - Rails - 如何在 Controller 内使用助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5130150/

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