2010-04-20 61 views
16

我试图使用delayed_job通过XMLrender_to_string在LIB类不工作

更新远程数据库在我的lib文件夹,我把同一个类文件应该做template.xml.builder一个render_to_text,但我得到:

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

我在做什么错?

回答

51
ac = ActionController::Base.new() 
ac.render_to_string(:partial => '/path/to/your/template', :locals => {:varable => somevarable}) 
+9

如果你试图用实例使用变量,像这样':locals => {:@instance_variable => value}' – 2013-05-15 02:13:14

+0

我得到Missing模板错误,好像它没有发现部分内容,我检查了很多次拼写。仍然没有..请帮助 – AirWick219 2014-09-27 06:16:13

+0

你会得到“Missing template”错误,因为ActionController :: Base会在'action_controller/base'路径中搜索。委托给另一个控制器。无论如何它通常会继承'ActionController :: Base'。 – 2014-10-15 08:57:16

3

render_to_string定义于ActionController::Base。由于类/模块定义在Rails控制器范围之外,因此该功能不可用。

你将不得不手动渲染文件。我不知道你在使用你的模板(ERB,Haml等)。但是你将会加载模板并自己解析它。

所以,如果雇员再培训局,这样的事情:

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的谐音效果很好。

+2

我得到的问题:未定义的方法'新”为Rails ::配置Module – 2011-09-26 05:48:24

4

我曾与一个不确定的辅助方法,然后我用的ApplicationController

ApplicationController.new.render_to_string 
+0

同样在这里。你有没有修复未定义的帮手? – nathanengineer 2015-05-03 18:29:56

+0

在我的情况下,我在调用AplicationController时忘记了一个名称空间。 我尝试: 'Usr :: ApplicationController.new.render_to_string' 它的工作原理。 – Germano 2015-05-04 19:40:26