lib类中的render_to_string不起作用

问题描述 投票:17回答:5

我正在尝试使用delayed_job通过xml更新远程数据库

在我的lib文件夹中,我放了一个文件,其中的类应该与render_to_text一起使用template.xml.builder,但我得到:

undefined method `render_to_string' for #<SyncJob:0x7faf4e6c0480>...

我究竟做错了什么?

ruby-on-rails templating
5个回答
55
投票
ac = ActionController::Base.new()
ac.render_to_string(:partial => '/path/to/your/template', :locals => {:varable => somevarable})

5
投票

我有一个未定义的辅助方法的问题,然后我使用ApplicationController

ApplicationController.new.render_to_string

3
投票

render_to_stringActionController::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

这是一般的想法。


2
投票

你可以将你的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 partials。


0
投票

Rails 5

render_to_string和其他人现在可以在控制器上作为类方法使用。因此,您可以使用您喜欢的任何控制器执行以下操作:ApplicationController.render_to_string

我特别需要根据对象的类为模板分配一个动态实例变量,所以我的例子看起来像:

ApplicationController.render_to_string(
  assigns: { :"#{lowercase_class}" => document_object },
  inline: '' # or whatever templates you want to use
)

制作导轨PR的开发人员的伟大博客文章:https://evilmartians.com/chronicles/new-feature-in-rails-5-render-views-outside-of-actions

© www.soinside.com 2019 - 2024. All rights reserved.