'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 1:[1]
Try this
format.csv do
response.headers["Content-Type"] = "text/csv; charset=UTF-8; header=present"
response.headers["Content-Disposition"] = "attachment; filename=invoices.csv"
end
Solution 2:[2]
Solution 3:[3]
I found other solution that worked for me (Rails 3.2 and Ruby 2.3.3)
- After generating the csv
report_csv = CSV.generate(col_sep: ";")...
- It can be downloaded from controller:
- Inside the block
format.csv
we could use
send_data(report_csv, filename: 'banana.csv')
- And we could access this action from a link that has the target blank
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | usha |
Solution 2 | deepfritz |
Solution 3 |