1
對不起我的英語,它不是我的母語。使用wickedpdf創建PDF並用回形針保存
我需要創建一個PDF文件(我可以使它現在),然後用曲別針將它保存(已安裝並與其他模型的工作)
我發現這個解決方案:
https://github.com/thoughtbot/paperclip/wiki/PDF-Email-Attachments-with-Paperclip-and-wicked_pdf
,但它使用一個已經創建的報告,我需要創建這個PDF,每次我創建一個新的記錄,我得到「爲nill類沒有方法,這樣也許這就是爲什麼沒有爲我工作。
我試着加入這個方法在「if @ instrument.save」裏面卻沒有奏效。
讓我告訴你我的代碼:
instrument.erb
class Instrument < ActiveRecord::Base
belongs_to :evaluation
has_attached_file :instrument_document
validates_attachment :instrument_document, content_type: { content_type: "application/pdf" }
do_not_validate_attachment_file_type :instrument_document
end
儀器#顯示
def show
respond_to do |format|
format.html { redirect_to instruments_url }
format.pdf do
render :pdf => "file.pdf", :template => 'instruments/instrument_document.html.erb', :margin => {:top => 15, :bottom =>15 },:header => { html: { template: 'instruments/header.pdf.erb', }}, :footer => { right: '[page]' }
end
end
end
儀器#創建
def create
@instrument = Instrument.new(instrument_params)
respond_to do |format|
if @instrument.save
# create an instance of ActionView, so we can use the render method outside of a controller
av = ActionView::Base.new()
av.view_paths = ActionController::Base.view_paths
# need these in case your view constructs any links or references any helper methods.
av.class_eval do
include Rails.application.routes.url_helpers
include ApplicationHelper
end
pdf_html = av.render template: 'instruments/instrument_document.html.erb'
# use wicked_pdf gem to create PDF from the doc HTML
doc_pdf = WickedPdf.new.pdf_from_string(
pdf_html,
page_size: 'Letter',
javascript_delay: 6000
)
# save PDF to disk
pdf_path = Rails.root.join('tmp/reports', "#{@instrument.id}_#{Date.today.iso8601}.pdf")
File.open(pdf_path, 'wb') do |file|
file << doc_pdf
end
@instrument.instrument_document = File.open pdf_path
@instrument.save!
# The report has now been saved elsewhere using Paperclip; we don't need to store it locally
File.delete(pdf_path) if File.exist?(pdf_path)
format.html { redirect_to @instrument, notice: 'Instrumento creado con éxito.' }
format.json { render :show, status: :created, location: @instrument }
else
format.html { render :new }
format.json { render json: @instrument.errors, status: :unprocessable_entity }
end
end
end
我越來越:
未定義方法`評估'爲零:NilClass
謝謝!