Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

model view controller - Rails create file and render

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

  1. create a file

  2. render a view or template to that file

  3. redirect_to or render another view

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.

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

thnx!

code:

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

end

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

and voila, no more error


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...