虽然我意识到应该在视图中使用一个助手,但在构建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助手?

推荐答案

Note:这是在Rails 2天内编写并接受的;如今,grosser's answer岁是一个不错的 Select .

Option 1:可能最简单的方法是将助手模块包含在控制器中:

class MyController < ApplicationController
  include MyHelper

  def xxxx
    @comments = []
    Comment.find_each do |comment|
      @comments << {:id => comment.id, :html => html_format(comment.content)}
    end
  end
end

Option 2:或者您可以将helper方法声明为类函数,并像这样使用它:

MyHelper.html_format(comment.content)

如果希望将其同时用作实例函数和类函数,可以在助手中声明这两个版本:

module MyHelper
  def self.html_format(str)
    process(str)
  end

  def html_format(str)
    MyHelper.html_format(str)
  end
end

希望这有帮助!

Ruby-on-rails相关问答推荐

Rails HotWire和View Components:涡轮框架不会取代内容

Rails Routing:在具有自己的路由的名称空间下组织路由

无法安装Ruby错误运行';__rvm_make-J4';,

ActiveAdmin:的呈现索引表在父级的显示页中有许多资源

为什么在使用 Ruby on Rails 时我的徽标没有出现在 Bootstrap 导航栏中?

如何在 Rails 3 中使用 Capybara 单击具有相同文本的第二个链接?

rails 3,简单数组的Kaminari分页

带有 Cucumber 和 rspec 的 BDD - 这什么时候是多余的?

使用回形针进行简单裁剪

如何更改 Heroku 应用程序的 DATABASE_URL

如何在rails中发回js.haml

如何解决弃用警告方法 to_hash 已弃用并将在 Rails 5.1 中删除

Rails:带参数的 URL/路径

counter_cache 实现的问题

我怎样才能看到水豚在失败的黄瓜步骤中发现了什么?

Rails 3 设计,current_user 在模型中不可访问?

Ruby 1.87 与 1.92 Date.parse

Rails 3:乘客找不到Bundle 程序安装的 git gem

如何为 Rails 迁移定义布尔字段

Rails:为什么 with_exclusive_scope 受保护?关于如何使用它的任何好的做法?