如何在Ruby on Rails中下载CSV文件?

Tin*_*n81 19 ruby csv ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.2

在我,InvoicesController我有这个:

def index
  @invoices = current_user.invoices
  respond_to do |format|
    format.html
    format.xls
    format.csv # not working!
  end
end
Run Code Online (Sandbox Code Playgroud)

在我index.html.erb看来,我有这两个下载链接:

<%= link_to "Download as Excel", invoices_path(:format => "xsl") %>
<%= link_to "Download as CSV", invoices_path(:format => "csv") %>
Run Code Online (Sandbox Code Playgroud)

模板index.xsl.erbindex.csv.erb不存在的.

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

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

谢谢你的帮助.

zea*_*soi 19

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

# 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
Run Code Online (Sandbox Code Playgroud)

  • 很高兴听到它有效.这是一个迂腐点,但你可以验证`render:template =>'发票/索引'(没有路径)是否也能正常工作?应该,AFAIK,我会相应地更新我的答案. (2认同)

ush*_*sha 6

尝试这个

format.csv do
  response.headers["Content-Type"] = "text/csv; charset=UTF-8; header=present"
  response.headers["Content-Disposition"] = "attachment; filename=invoices.csv"
end
Run Code Online (Sandbox Code Playgroud)