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

标签 ruby-on-rails ruby-on-rails-3 ruby-on-rails-5

虽然我意识到您应该在 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/

相关文章:

ruby-on-rails - 福雷姆 gem : how to link a forum to other models

ruby-on-rails - before_create 不起作用

ruby-on-rails - Omnisocial 依赖于 gem bcrypt-ruby 2.1,但 Rails 3.1 依赖于 bcrypt 3.0.0 - 我该怎么办?

ruby-on-rails - 如何在 Rails 中添加插件?

ruby - 如何使用 Ruby on Rails 发出 HTTP 请求?

javascript - 如何在 ruby​​ on Rails 5.2.3 中包含 javascript?

ruby-on-rails - 禁用卡住的字符串文字注释检查

ruby-on-rails - 如何覆盖 form_for 助手中的类名?

ruby-on-rails - 如何在 Controller 中呈现 View 并分配给变量 (Rails)

postgresql - 如何使用多个键和值 rails 5 将数据存储在 hstore 数据类型中