ersamy
ersamy

Reputation: 451

Rails: How to create a file from a controller and save it in the server?

For some strange reason I need to save a file (normally downloaded directly) in the server. In my case I have a PDF file created with PDFKit that I need to keep.

# app/controllers/reports_controller.rb
def show
  @report = Report.find(params[:id])

  respond_to do |format|
    format.pdf { render :text => PDFKit.new(report_url(@report)).to_pdf }
  end
end

If I go to reports/1.pdf I get the report I am expecting but I want to keep it in the server.

Is there a Raily way to save a file in the server from a respond to?

Upvotes: 3

Views: 2016

Answers (1)

Jordan Running
Jordan Running

Reputation: 106147

Just a quick note before I get to the actual answer: It looks like you're passing a fully-qualified URL (report_url(@report)) to PDFKit.new, which is a waste--it means PDFKit has to make a request to the web server, which in turn needs to go through Rails' router and so on down the line to fetch the contents of the page. Instead you should just render the page inside your controller with render_to_string and pass it to PDFKit.new, since it will accept an HTML string. Keeping that in mind...

This is covered in the "Usage" section of PDFKit's README. You would do something like this:

def show
  @report = Report.find(params[:id])

  kit       = PDFKit.new render_to_string(@report) # pass any options that the
  pdf_file  = kit.to_file '/some/file/path.pdf'    # renderer needs here (same
                                                   # options as `render`).
  # and if you still want to send it to the browser...
  respond_to do |format|
    format.pdf { render :file => pdf_file.path }
  end
end

Upvotes: 2

Related Questions