虽然我意识到你应该在视图中使用一个帮助器,但我需要在我的控制器中使用一个帮助器,因为我正在构建一个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助手?


当前回答

class MyController < ApplicationController
    # include your helper
    include MyHelper
    # or Rails helper
    include ActionView::Helpers::NumberHelper

    def my_action
      price = number_to_currency(10000)
    end
end

在Rails 5+中,只需使用helper (helpers.number_to_currency(10000))

其他回答

我的问题用选项1解决了。可能最简单的方法是在控制器中包含你的helper模块:

class ApplicationController < ActionController::Base
  include ApplicationHelper

...

一般来说,如果helper只在控制器中使用,我更倾向于将它声明为类ApplicationController的实例方法。

其他答案中缺少的一个选择是,你可以反过来:在你的Controller中定义你的方法,然后使用helper_method使它在视图中也可用,你知道,一个帮助方法。

例如:


class ApplicationController < ActionController::Base

private

  def something_count
    # All other controllers that inherit from ApplicationController will be able to call `something_count`
  end
  # All views will be able to call `something_count` as well
  helper_method :something_count 

end

在Rails 5+中,您可以简单地使用下面演示的简单示例函数:

module ApplicationHelper
  # format datetime in the format #2018-12-01 12:12 PM
  def datetime_format(datetime = nil)
    if datetime
      datetime.strftime('%Y-%m-%d %H:%M %p')
    else
      'NA'
    end
  end
end

class ExamplesController < ApplicationController
  def index
    current_datetime = helpers.datetime_format DateTime.now
    raise current_datetime.inspect
  end
end

输出 “2018-12-10 01:01 am”

你可以使用

帮手。<helper>在Rails 5+(或ActionController::Base.helpers.<helper>) view_context。<helper> (Rails 4 & 3)(警告:每次调用都会实例化一个新的视图实例) @template。<helper> (Rails 2) 在单例类中包含helper,然后在单例类中包含single .helper 在控制器中包含helper(警告:将使所有的helper方法成为控制器动作)