当我意识到你应该在视图中使用帮助器时,我需要一个帮助器在我的控制器中,因为我正在构建一个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
助手?
注意:这是在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
希望这可以帮助!
您可以使用
helpers.<helper>
)中的ActionController::Base.helpers.<helper>
view_context.<helper>
(Rails 4和3)(警告:这会实例化每个调用的新视图实例)@template.<helper>
(Rails 2)singleton.helper
include
控制器中的帮助器(警告:将所有辅助方法转换为控制器操作)在Rails 5中,在控制器中使用helpers.helper_function
。
例:
def update
# ...
redirect_to root_url, notice: "Updated #{helpers.pluralize(count, 'record')}"
end
资料来源:@Markus对另一个答案的评论。我觉得他的答案应该得到答案,因为这是最干净,最简单的解决方案。
使用选项1解决了我的问题。可能最简单的方法是在控制器中包含辅助模块:
class ApplicationController < ActionController::Base
include ApplicationHelper
...
通常,如果要在(仅)控制器中使用帮助器,我更喜欢将其声明为class ApplicationController
的实例方法。
在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
OUTPUT
"2018-12-10 01:01 AM"
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+中只需使用帮助程序(helpers.number_to_currency(10000))