【发布时间】:2011-02-10 07:20:37
【问题描述】:
我正在尝试使用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>...
我做错了什么?
【问题讨论】:
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 公关的开发人员的精彩博文:https://evilmartians.com/chronicles/new-feature-in-rails-5-render-views-outside-of-actions
【讨论】:
我在使用未定义的辅助方法时遇到了问题,然后我使用了ApplicationController
ApplicationController.new.render_to_string
【讨论】:
Usr::ApplicationController.new.render_to_string 它有效。
ac = ActionController::Base.new()
ac.render_to_string(:partial => '/path/to/your/template', :locals => {:varable => somevarable})
【讨论】:
:locals => {:@instance_variable => value}
ActionController::Base 将在 action_controller/base 路径中搜索。委托给另一个控制器。无论如何,它通常都会继承ActionController::Base。
您可以将您的 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 部分。
【讨论】:
render_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 的docs。
这就是一般的想法。
【讨论】: