0

我目前有一個使用wicked_pdf和carrierwave功能的rails應用程序(4.2.1)。用戶當前點擊一個按鈕,將家庭評估視圖呈現爲PDF,然後用戶將PDF下載到他們的計算機,然後導航到評估表單,然後他們提交PDF併成功上傳到AWS。使用wicked_pdf創建pdf並傳遞給carrierwave進行上傳

這一切都很好,但我想要做的是「簡化」這個過程。當用戶點擊一個按鈕時,PDF就會被創建並傳遞給carrierwave,以便使用carrierwave/fog上傳到AWS。我現在有一個鏈接到調用FamilyAssesment.upload_assessment方法的控制器。

我一直在嘗試不同的方法,但似乎無法完全理解我需要做些什麼才能使其工作。

上查看按鈕

<%= link_to "Upload", family_assessment_pdf_upload_url(id: "#{f.object.case.id}"), class: 'button radius default tiny pdf-button' %> 

family_assessments_controller.rb

class FamilyAssessmentsController < ApplicationController 

    def family_assessment_pdf_upload 
    c = Case.find(params[:id]) 
    family_assessment = c.family_assessment 
    assessment = c.assessments.where(title: 'Families First Assessment').first 

    FamilyAssessment.upload_assessment(assessment, family_assessment) 

    #If work is done and url saved to assessment.assessment do some redirect action here 

    end 

end 

family_assessment.rb

class FamilyAssessment < ActiveRecord::Base 

    def self.upload_assessment(assessment, family_assessment) 
    family_assessment = family_assessment 
    assessment = assessment 

    #I think this is how I would create the PDF in preparation for hand off to carrierwave 

    pdf = WickedPdf.new.pdf_from_string(
     render_to_string(:pdf => "family_assessment",:template => 'family_assessments/family_assessment.pdf.erb', :locals => {:family_assessment => family_assessment}) 
    ) 

    #Pass pdf to carrierwave and save url in assessment.assessment 

    end 

end 

回答

1

看起來你可以將PDF保存到臨時文件,然後上傳該臨時文件。

class FamilyAssessment < ActiveRecord::Base 

    def self.upload_assessment(assessment, family_assessment) 
    family_assessment = family_assessment 
    assessment = assessment 

    #I think this is how I would create the PDF in preparation for hand off to carrierwave 

    pdf = WickedPdf.new.pdf_from_string(
     render_to_string(:pdf => "family_assessment",:template => 'family_assessments/family_assessment.pdf.erb', :locals => {:family_assessment => family_assessment}) 
    ) 

    #Pass pdf to carrierwave and save url in assessment.assessment 
    # Write it to tempfile 
    tempfile = Tempfile.new("#{Rails.root}/tmp/assessment_#{self.id}.pdf") 
    tempfile.binmode 
    tempfile.write pdf_file 
    tempfile.close 

    # Attach that tempfile to the invoice 
    unless pdf_file.blank? 
     self.uploads.clear 
     self.uploads.create(fileinfo: File.open(tempfile.path), job_id: self.job.id) 
     tempfile.unlink 
    end 

    end 

end 

這個答案的很多來自Getting PDF from WickedPDF for attachment via Carrierwave

+0

我得到的東西像'沒有這樣的文件或目錄@ rb_sysopen - /var/folders/_0/f6fqddzx6sx64kkpf0l540sr0000gn/T/{Rails.root}/tmp/ invoice_78.pdf20170502-46739-59eta1'。你會知道如何解決這個問題嗎? –

+0

@ Code-MonKy - 他有幾個錯別字。該行應該是'「#{Rails.root}/tmp/...」'。注意缺少'#' – toobulkeh

+0

我修正了前面提到的錯字。 – nzajt