Note that there are some explanatory texts on larger screens.

plurals
  1. POExport CSV with Mongoid and FasterCSV
    text
    copied!<pre><code>Class UserController def export_users users = User.all stream_csv do |csv| csv &lt;&lt; ["Name","Email","Gender"] users.each do |i| csv &lt;&lt; [i.name,i.email,i.gender] end end end def stream_csv require 'fastercsv' filename = params[:action] + ".csv" #this is required if you want this to work with IE if request.env['HTTP_USER_AGENT'] =~ /msie/i headers['Pragma'] = 'public' headers["Content-type"] = "text/plain" headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0' headers['Content-Disposition'] = "attachment; filename=\"#{filename}\"" headers['Expires'] = "0" else headers["Content-Type"] ||= 'text/csv' headers["Content-Disposition"] = "attachment; filename=\"#{filename}\"" controller.response.headers["Content-Transfer-Encoding"] = "binary" end render :text =&gt; Proc.new { |response, output| csv = FasterCSV.new(output, :row_sep =&gt; "\r\n") yield csv } end end </code></pre> <p>Err: "#Proc:0x9382539@/sites/app/controllers/export_controller.rb:56"</p> <p>Using Ruby 1.8 and Rails 3.0.9</p> <p>So I think the problem here is that I'm not using "Proc" right. Or it's not supposed to act like just another block...</p> <p>I thought about programming a new logic into the class so that reads better. But if somebody could explain to me why my code is wrong or at least point me in a new direction than I might be able to learn something new here. Thanks</p> <p><strong>Note: Found a better way:</strong></p> <pre><code>def export_inverts require 'fastercsv' inverts = Invert.all filename = params[:action] + ".csv" #this is required if you want this to work with IE if request.env['HTTP_USER_AGENT'] =~ /msie/i headers['Pragma'] = 'public' headers["Content-type"] = "text/plain" headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0' headers['Content-Disposition'] = "attachment; filename=\"#{filename}\"" headers['Expires'] = "0" else headers["Content-Type"] ||= 'text/csv' headers["Content-Disposition"] = "attachment; filename=\"#{filename}\"" headers["Content-Transfer-Encoding"] = "binary" end csv_string = FasterCSV.generate do |csv| csv &lt;&lt; ["Genus","Species","Common Name","Pet Name","Gender"] inverts.each do |i| csv &lt;&lt; [i.scientific_name,i.scientific_name,i.common_name,i.pet_name,i.gender] end end render :text =&gt; csv_string end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload