Rails创建文件并渲染 [英] Rails create file and render

查看:76
本文介绍了Rails创建文件并渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在rails中,是否有一种方法(在控制器中)可以实现:

In rails, is there a way (in a controller) to:

  1. 创建文件

  1. create a file

render该文件的视图或模板

我尝试了各种构造,但始终遇到相同的错误:此操作多次调用了渲染和/或重定向.请注意,您只能调用渲染或重定向,每个操作最多只能调用一次.

I've tried all kinds of constructions, but keep getting the same error: Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action.

否则;是否可以render模板或视图文件而不显示该模板/视图?

Otherwise; is it possible to render a template or view to a file without displaying that template/view?

thnx!

代码:

def get_report

# part 1: create and render file for use with phantomjs 

File.new('./vendor/assets/javascripts/graph_disk1.json','w') {|f| f.write(render "reports/disk", :layout => false)}
system `phantomjs ./vendor/assets/javascripts/highcharts-convert.js -infile ./vendor/assets/javascripts/graph_disk1.json -outfile ./app/assets/images/chart01.png -options ./vendor/assets/javascripts/resources.json`    

# part 2: create odf-report and use image created bij phantomjs/highcharts-convert

report = ODFReport::Report.new("#{Rails.root}/app/report_templates/PSC2_KalScanV0.odt") do |r|
  r.add_image :graphd1, "#{Rails.root}/app/assets/images/chart01.png" 
  send_data report.generate, type: 'application/vnd.oasis.opendocument.text',
                        disposition: 'attachment',
                          filename: 'report.odt'
  end

结束

这两个部分各起作用,但不能像这样被调用(在1个操作/控制器中)起作用.

the 2 parts work each, but not when called liked this (in 1 action/controller).

推荐答案

找到解决方案总是很容易的:

The solution is always easy once you've found it:

代替:f.write(render "reports/disk", :layout => false)

使用:f.write(render_to_string "reports/disk", :layout => false)

瞧,别再错误

这篇关于Rails创建文件并渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆