title: Rails - CSV export: prompt for file download
body: <p>I want to give my users the ability to export a table to CSV.</p>
  
  <p>So in my controller, I've added on top of the file:</p>
  
  <pre><code>  respond_to :html, :js, :csv
  </code></pre>
  
  <p>I'm also setting the headers if the requested format is csv:</p>
  
  <pre><code>if params[:format] == 'csv'
    generate_csv_headers("negotiations-#{Time.now.strftime("%Y%m%d")}") 
  end
  </code></pre>
  
  <p>Code for <code>generate_csv_headers</code>(in application_controller) is:</p>
  
  <pre><code>  def generate_csv_headers(filename)
      headers.merge!({
        'Cache-Control'             =&gt; 'must-revalidate, post-check=0, pre-check=0',
        'Content-Type'              =&gt; 'text/csv',
        'Content-Disposition'       =&gt; "attachment; filename=\"#{filename}\"",
        'Content-Transfer-Encoding' =&gt; 'binary'
      })
    end
  </code></pre>
  
  <p>I've also created a view named <code>index.csv.erb</code> to generate my file:</p>
  
  <pre><code>&lt;%- headers = ["Id", "Name"] -%&gt;
  &lt;%= CSV.generate_line headers %&gt;
  &lt;%- @negotiations.each do |n| -%&gt;
  &lt;%- row = [ n.id,
              n.name ] -%&gt;
  &lt;%=   CSV.generate_line row %&gt;
  &lt;%- end -%&gt;
  </code></pre>
  
  <p>I don't have any error, but it simply displays the content of the CSV file, while I'd expect a prompt from the browser to download the file.</p>
  
  <p>I've read a lot, but could not find anything that'd work.
  Do you have an idea?</p>
  
  <p>thanks, p.</p>