Rails 3 - set the filename in a respond_to

Deadly 提交于 2019-12-03 10:01:37
Grant Birchmeier

I got it, thanks to some help from this answer.

format.csv do
  response.headers['Content-Disposition'] = 'attachment; filename="' + filename + '.csv"'
  render "summary/report.csv.erb"
end

First you set the filename in the response header, then you call render.

(The template param to render is optional, but in my case I needed it.)

You can pass the filename to send_data and let it handle the Content-Disposition header.

# config/initializers/csv_support.rb
ActionController::Renderers.add :csv do |csv, options|
  options = options.reverse_merge type: Mime::CSV
  content = csv.respond_to? :to_csv ? csv.to_csv : csv.to_s
  send_data content, options
end

# app/controllers/reports_controller.rb
respond_to do |format|
  format.html ...
  format.csv { render csv: my_report, filename: 'my_report.csv' }
end

Then add a to_csv method to my_report or pass a pre-generated CSV string.

Alternatively you can use a combination of send_data and render_to_string (since you have a CSV template).

def report
  respond_to do |format|
    format.html
    format.csv do
      send_data render_to_string(:template => "summary/report.csv.erb"),
             :filename => "foo"
    end
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!