ruby-on-railsrubyruby-on-rails-3csvruby-on-rails-3.2

How to download a CSV file in Ruby on Rails?


In my InvoicesController I have this:

def index
  @invoices = current_user.invoices
  respond_to do |format|
    format.html
    format.xls
    format.csv # not working!
  end
end

In my index.html.erb view I have these two download links:

<%= link_to "Download as Excel", invoices_path(:format => "xsl") %>
<%= link_to "Download as CSV", invoices_path(:format => "csv") %>

The templates index.xsl.erb and index.csv.erb do exist as well.

The first link works, i.e. the Excel file gets downloaded to the user's computer. However, the CSV file is rendered in the browser and not downloaded.

What must I do to enable users to download CSV files as well?

Thanks for any help.


Solution

  • Try specifying the appropriate content headers and explicitly rendering your index.csv.erb template in your format.csv handler block.

    # app/controllers/invoices_controller.rb
    format.csv do
        response.headers['Content-Type'] = 'text/csv'
        response.headers['Content-Disposition'] = 'attachment; filename=invoice.csv'    
        render :template => "path/to/index.csv.erb"
    end