【问题标题】:Link to CSV rendering as HTML链接到以 HTML 格式呈现的 CSV
【发布时间】:2019-04-08 17:54:54
【问题描述】:

我的 rails 应用程序中有一个链接应该导出 CSV。但是当我单击链接时,它会将页面重新加载为 html。我尝试将response.headers['Content-Type'] = 'text/csv' response.headers['Content-Disposition'] = 'attachment; filename=invoice.csv' 添加到控制器,但这无济于事。

控制器

def index

  respond_to do |format|
    format.html
    format.csv do
      response.headers['Content-Type'] = 'text/csv'
      response.headers['Content-Disposition'] = 'attachment; filename=custome_incentives.csv'
      send_data @incentives.to_csv
    end
  end
end

erb

<%= link_to 'Download to CSV', incentives_path(property.slug, format: :csv), class: 'btn csv' %>

更新

我尝试在 format.csv 块中放置一个 binding.pry,但它没有触发。

【问题讨论】:

  • 你不需要那些标题,只需设置类型和文件名:send_data @incentives.to_csv, type: 'text/csv', filename: 'myfile.csv'。
  • @CAmador 这仍然给了我同样的回应。
  • byebug/log that format.csv,该块真的在运行吗?
  • @CAmador 它没有被击中
  • 为导出设置一个新动作,或者注释掉除了调用 send_data 之外的所有 respond_to 东西

标签: ruby-on-rails ruby export-to-csv


【解决方案1】:

假设路线都井井有条,你有tried this way这样的filename吗?

def index

  respond_to do |format|
    format.html
    format.csv do
      send_data @incentives.to_csv, filename: 'custome_incentives.csv'
    end
  end
end

如果这不起作用,也可以force a download link。

【讨论】:

  • 没用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-20
相关资源
最近更新 更多