我正在尝试使用delayed_job
通过xml更新远程数据库。
我在我的lib文件夹中放置了一个类文件,该文件应该使用template.xml.builder
执行render_to_text
操作,但是我遇到了以下问题:
undefined method `render_to_string' for #<SyncJob:0x7faf4e6c0480>...
我做错了什么?
我正在尝试使用delayed_job
通过xml更新远程数据库。
我在我的lib文件夹中放置了一个类文件,该文件应该使用template.xml.builder
执行render_to_text
操作,但是我遇到了以下问题:
undefined method `render_to_string' for #<SyncJob:0x7faf4e6c0480>...
我做错了什么?
ac = ActionController::Base.new()
ac.render_to_string(:partial => '/path/to/your/template', :locals => {:varable => somevarable})
ApplicationController
。ApplicationController.new.render_to_string
Usr::ApplicationController.new.render_to_string
然后它就可以工作了。 - Germanorender_to_string
定义在ActionController :: Base
中。由于该类/模块是在Rails控制器范围之外定义的,因此函数不可用。
您将需要手动渲染文件。我不知道您在模板方面使用的是什么(ERB,Haml等)。但是您需要加载模板并自己解析它。
如果是ERB,则可以像这样:
require 'erb'
x = 42
template = ERB.new <<-EOF
The value of x is: <%= x %>
EOF
puts template.result(binding)
ERB.new
,但这是留给你的练习。以下是ERB的文档。render_to_string
等方法现在作为控制器的类方法可用。因此,您可以在任何喜欢的控制器中执行以下操作:ApplicationController.render_to_string
我特别需要根据对象的类分配动态实例变量到模板中,所以我的示例看起来像:
ApplicationController.render_to_string(
assigns: { :"#{lowercase_class}" => document_object },
inline: '' # or whatever templates you want to use
)
这是一篇很棒的博客文章,介绍了制作rails PR的开发人员。文章链接:https://evilmartians.com/chronicles/new-feature-in-rails-5-render-views-outside-of-actions
template.xml.builder
转化为一个局部文件(_template.xml.builder
),然后通过实例化一个ActionView::Base
对象并调用render
方法来渲染它。av = ActionView::Base.new(Rails::Configuration.new.view_path)
av.extend ApplicationController.master_helper_module
xml = av.render :partial => 'something/template'
我还没有尝试过用xml,但是它可以很好地处理html局部文件。
:locals => {:@instance_variable => value}
。 - Jason KimActionController::Base
将在action_controller/base
路径中搜索。委托给另一个控制器。通常它会继承ActionController::Base
。 - denis.peplin:partial =>
部分,像这样:ac.render_to_string('/path/to/your/template', :locals => {:varable => somevarable})
(请注意,路径是从/views目录内开始的,例如,您可以有'users/index.html.erb'
)。 - stevec