如何在Ruby on Rails中下载CSV文件?
问题描述:
在我的 InvoicesController
中有以下内容:
def index
@invoices = current_user.invoices
respond_to do |format|
format.html
format.xls
format.csv # not working!
end
end
在我的 index.html .erb
查看我有这两个下载链接:
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") %>
模板 index.xsl.erb
index.csv.erb
也存在。
第一个链接工作,即Excel文件被下载用户的计算机。
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.
我必须采取什么措施才能让使用者下载CSV档案?
What must I do to enable users to download CSV files as well?
感谢您的帮助。
答
尝试指定适当的内容 index.csv.erb
模板显示和块。
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