Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在RubyonRails中下载CSV文件?_Ruby On Rails_Ruby_Ruby On Rails 3_Csv_Ruby On Rails 3.2 - Fatal编程技术网

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

Ruby on rails 如何在RubyonRails中下载CSV文件?,ruby-on-rails,ruby,ruby-on-rails-3,csv,ruby-on-rails-3.2,Ruby On Rails,Ruby,Ruby On Rails 3,Csv,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 在我的index.html.erb视图中,我有以下两个下载链接: <%= link_to "Download as Excel", invoices_pa

在我的
InvoicesController
中,我有:

def index
  @invoices = current_user.invoices
  respond_to do |format|
    format.html
    format.xls
    format.csv # not working!
  end
end
在我的
index.html.erb
视图中,我有以下两个下载链接:

<%= link_to "Download as Excel", invoices_path(:format => "xsl") %>
<%= link_to "Download as CSV", invoices_path(:format => "csv") %>
“xsl”)%%>
“csv”)%%>
模板
index.xsl.erb
index.csv.erb
也确实存在

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

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

谢谢你的帮助。

试试这个

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

尝试指定适当的内容标题并在
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
我最近发现

render_csv

也许可以看看这个(耶)

谢谢!我试过了,但它没有下载,甚至没有在浏览器中显示文件。当我点击链接时,什么也没有发生。我也在上面添加了我的
index.csv.erb
文件的内容。您是否需要在初始化器中使用Ruby的原生csv库?谢谢!这就成功了。似乎您真的必须显式指定模板名称,尽管我花了一段时间才找到正确的语法:
render“#{Rails.root}/app/views/invoices/index.csv.erb”
我相应地更改了您的答案。很高兴听到它起作用。这是一个迂腐的观点,但您能否验证
render:template=>“invoices/index”
(不带路径)是否也能正常工作?应该是这样的,好吧,我会相应地更新我的答案。我还必须添加:layout=>false