AnA*_*ice 198 ruby-on-rails ruby-on-rails-3 ruby-on-rails-5
当我意识到你应该在视图中使用帮助器时,我需要一个帮助器在我的控制器中,因为我正在构建一个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
Run Code Online (Sandbox Code Playgroud)
我怎样才能访问我的html_format
助手?
gro*_*ser 286
您可以使用
Xav*_*olt 202
注意:这是在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
Run Code Online (Sandbox Code Playgroud)
选项2:或者您可以将辅助方法声明为类函数,并像这样使用它:
MyHelper.html_format(comment.content)
Run Code Online (Sandbox Code Playgroud)
如果您希望能够将它用作实例函数和类函数,则可以在助手中声明这两个版本:
module MyHelper
def self.html_format(str)
process(str)
end
def html_format(str)
MyHelper.html_format(str)
end
end
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
Ger*_*haw 78
在Rails 5中使用helpers.helper_function
您的控制器.
例:
def update
# ...
redirect_to root_url, notice: "Updated #{helpers.pluralize(count, 'record')}"
end
Run Code Online (Sandbox Code Playgroud)
资料来源:@Markus对另一个答案的评论.我觉得他的答案应该得到答案,因为这是最干净,最简单的解决方案.
参考:https://github.com/rails/rails/pull/24866
小智 10
使用选项1解决了我的问题.可能最简单的方法是在控制器中包含辅助模块:
class ApplicationController < ActionController::Base
include ApplicationHelper
...
Run Code Online (Sandbox Code Playgroud)
在 Rails 5 之前,您必须包含辅助模块。
在较新的版本中,您可以将控制器中的助手与助手(复数)对象一起使用。
class UsersController
def index
helpers.my_helper_method_name(even_pass_arg_here)
end
end
Run Code Online (Sandbox Code Playgroud)
https://www.rubyguides.com/2020/01/rails-helpers/
归档时间: |
|
查看次数: |
162973 次 |
最近记录: |