Rails - 如何在控制器中使用助手 [英] Rails - How to use a Helper Inside a Controller

查看:36
本文介绍了Rails - 如何在控制器中使用助手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我意识到您应该在视图中使用帮助程序,但我需要在控制器中使用帮助程序,因为我正在构建要返回的 JSON 对象.

While I realize you are supposed to use a helper inside a view, I need a helper in my controller as I'm building a JSON object to return.

有点像这样:

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 助手?

How can I access my html_format helper?

推荐答案

注意: 这是在 Rails 2 天内编写并接受的;现在格罗瑟的答案是要走的路.

Note: This was written and accepted back in the Rails 2 days; nowadays grosser's answer is the way to go.

选项 1: 可能最简单的方法是将您的辅助模块包含在您的控制器中:

Option 1: Probably the simplest way is to include your helper module in your controller:

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

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

Option 2: Or you can declare the helper method as a class function, and use it like so:

MyHelper.html_format(comment.content)

如果您希望能够将它用作实例函数和类函数,您可以在您的助手中声明这两个版本:

If you want to be able to use it as both an instance function and a class function, you can declare both versions in your helper:

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

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

希望这会有所帮助!

这篇关于Rails - 如何在控制器中使用助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆