230

ビュー内でヘルパーを使用することになっていることはわかっていますが、返される 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ヘルパーにアクセスするにはどうすればよいですか?

4

10 に答える 10

337

使用できます

  • helpers.<helper>Rails 5+ (またはActionController::Base.helpers.<helper>)
  • view_context.<helper>( Rails 4 & 3 ) (警告: これにより、呼び出しごとに新しいビュー インスタンスがインスタンス化されます)
  • @template.<helper>(レール 2 )
  • シングルトンクラスにヘルパーを含めてからsingleton.helper
  • includeコントローラーのヘルパー (警告: すべてのヘルパー メソッドがコントローラー アクションになります)
于 2012-06-22T18:00:11.393 に答える
222

注:これは、Rails 2 日後に作成され、受け入れられました。今日ではグロスの答えが道です。

オプション 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

オプション 2:または、ヘルパー メソッドをクラス関数として宣言し、次のように使用することもできます。

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

お役に立てれば!

于 2011-02-26T23:09:13.770 に答える
10

私の問題はオプション 1 で解決しました。おそらく最も簡単な方法は、コントローラーにヘルパー モジュールを含めることです。

class ApplicationController < ActionController::Base
  include ApplicationHelper

...
于 2016-02-26T16:11:33.897 に答える