如何在Ruby on Rails 3.2.8中渲染XML模板并使用SEND_DATA?

15

有人能帮我解决XML模板渲染和send_data的问题吗?

我有一个控制器:

def show
  @calculation = Calculation.find(params[:id])

  respond_to do |format|
    format.html # show.html.erb
    format.json { render json: @calculation }
    format.xml {send_data( :partial=>show.xml.erb, :filename => "my_file.xml" ) }
    format.pdf { render :format=>false}
  end
end
但是我在使用时遇到了许多“堆栈层级过深”的错误。
如果我使用

{send_data( @calculation, :filename => "my_file.xml" ) }

我得到了一个XML文件,但不是来自我的模板...

编辑: 我找到了一种方法!

format.xml do  
  stream = render_to_string(:template=>"calculations/show" )  
  send_data(stream, :type=>"text/xml",:filename => "test.xml")
end

一切都正常工作!


你能贴出完整的跟踪吗? - sunnyrjuneja
CalculationsController#show 中的 SystemStackError堆栈级别太深 Rails 根目录: C:/RubyStack-3.2.5-0/examplexml应用跟踪 | 框架跟踪 | 完整跟踪 actionpack (3.2.5) lib/action_dispatch/middleware/reloader.rb:70 - Dmitry
1
我可以在Chrome中使用以下代码获得结果:format.xml { render :format=>false}但只能在屏幕上显示,无法下载文件。 - Dmitry
嘿,Dmitry,考虑发布你的问题并将其标记为解决方案。 - sunnyrjuneja
@Dmitry - 如果你愿意将解决方案总结为自己的答案,我会删除我的回答。(请参见http://meta.stackexchange.com/questions/90263/unanswered-question-answered-in-comments,了解为什么这很有帮助。)谢谢! - DreadPirateShawn
2个回答

21

复制编辑后的问题内容中的答案,以便将该问题从“未回答”过滤器中移除:

format.xml do  
  stream = render_to_string(:template=>"calculations/show" )  
  send_data(stream, :type=>"text/xml",:filename => "test.xml")
end

~ 回答来自 Dmitry


0
您可以在Rails 5中尝试这个。
respond_to do |format|
  format.html do
    stream = render_to_string(:template => "calculations/test.xml.builder")
    send_data stream,
              :type => 'text/xml; charset=UTF-8;',
              :disposition => "attachment; filename=test.xml"
  end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接