Steve Q
Steve Q

Reputation: 395

Saving a PDF to file

I have code to write a file to save a PDF and then upload it to s3. What I have works perfectly in dev. but not in production.

def upload_to_s3(pdf)
  save_path = "#{Rails.root}/tmp/pdfs/invoice_#{@invoice.id}.pdf"
  f = File.new(save_path, 'w:ASCII-8BIT')
  f.write(pdf)
  uploader = InvoiceUploader.new
  File.open(save_path) { |file| uploader.store!(file) }
  @invoice.update(pdf: uploader.url)
  File.delete(save_path)
  uploader.url
end

Stack Trace:

Rendered invoices/pdf.html.erb (6.5ms)
Completed 500 Internal Server Error in 1420ms (ActiveRecord: 34.6ms)
Errno::ENOENT (No such file or directory @ rb_sysopen - /home/deploy/reputation/releases/20180401031049/tmp/pdfs/invoice_2.pdf):
app/controllers/api/v1/invoices_controller.rb:140:in `initialize'
[5e443877-e7fe-4848-847b-f5f6159e7db9] 
app/controllers/api/v1/invoices_controller.rb:140:in `new'
[5e443877-e7fe-4848-847b-f5f6159e7db9] 
app/controllers/api/v1/invoices_controller.rb:140:in `upload_to_s3'
[5e443877-e7fe-4848-847b-f5f6159e7db9] 
app/controllers/api/v1/invoices_controller.rb:65:in `pdf'

Upvotes: 0

Views: 589

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

The error message clearly states:

Errno::ENOENT (No such file or directory @ rb_sysopen - /home/deploy/reputation/releases/20180401031049/tmp/pdfs/invoice_2.pdf): ...

Create the directory /home/deploy/reputation/releases/20180401031049/tmp/pdfs/ in production upfront. Since it’s dynamic (dependent on the release datetime,) it’s better to create it in your ruby code:

save_dir = "#{Rails.root}/tmp/pdfs/"
Dir.mkdir(save_dir)

save_path = ...

Upvotes: 3

Related Questions