如何在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视图中,我有以下两个下载链接:

  "xsl") %>  "csv") %> 

模板index.xsl.erbindex.csv.erb也存在。

第一个链接有效,即Excel文件被下载到用户的计算机。 但是,CSV文件在浏览器中呈现而不是下载。

我还必须做些什么才能让用户下载CSV文件?

谢谢你的帮助。

尝试指定相应的内容标头, format.csv处理程序块中显式呈现index.csv.erb模板。

 # 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 

试试这个

 format.csv do response.headers["Content-Type"] = "text/csv; charset=UTF-8; header=present" response.headers["Content-Disposition"] = "attachment; filename=invoices.csv" end 

我最近发现了

 render_csv 

也许看看这个railscast (yay)