4

Wow, what a great site! I hope this question meets the requirements :-)

Generally, this question is about how to set response headers in Rails when using the render method. Specifically, I have a markdown version of a document, which I would like the browser to save as a file by default, rather than display. I have found that you can set headers with the head method, like this:

respond_to do |format|
  format.html {...
  format.text { head(:content_disposition => "attachment") }
end

But the options for render don't work like this and I can't find anything to access the headers beforehand from the controller. Could anybody offer advice?

Thanks for taking the time to read my question.

Matt Gibb
  • 41
  • 1
  • 2
  • I was surprised how difficult it was to find information on this: `response.headers[key] = value` is the trick. – Mulan Aug 15 '13 at 19:23

2 Answers2

2

yes use #headers method

respond_to do |format|
  format.html {...
  format.text do
    headers[:content_disposition] = "attachment; filename=\"filename.ext\""
    render...
  end
end
firien
  • 1,548
  • 16
  • 23
0

I wasn't sure what the answer was, but this quick search of other articles came up with this: Rails; save a rendered views html content to file

Does that do the trick?

Community
  • 1
  • 1
Jo P
  • 1,656
  • 21
  • 25
  • 2
    Hey Jo! Yeah send_data is a good way I wasn't aware of, another one is to specify the header with the response object: ```response.headers['Content-Disposition'] = 'attachment; filename=foo.md'``` – Matt Gibb Aug 04 '11 at 13:54
  • Ah in the source for response it says to use `ActionController::Base#headers` instead. I think it's defined here, but I can't profess to understand completely what's going on: https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal.rb – Matt Gibb Aug 04 '11 at 14:21