我正在建立一个客户数据库/发票系统。当发票准备好使用PDFKit转换为可打印的PDF时,可以通过包含复选框的表单从发票索引中选择发票,这些复选框通过selected_invoices参数传递发票ID。我想重新使用该方法并同时为这些特定发票创建PDF地址标签。我似乎无法弄清楚我在哪里出错了。当调用“标签”方法时,它无法从参数中查看发票ID。
以下是代码的相关部分:
def generate_multiple_pdfs
#generate pdfs from selected invoices and save each to file
@invoices = Invoice.find(params[:selected_invoices])
files = []
@invoices.each do |invoice|
path = show_pdf_invoice_url(invoice)
filename = "invoice_#{invoice.id}.pdf"
files.push filename
kit = PDFKit.new(path)
pdf = kit.to_file("#{Rails.root}/public/invoices/#{filename}")
end
#generate address labels for selected invoices
path = labels_invoices_url
filename = "invoice_labels#{Date.today.to_formatted_s(:iso8601)}.pdf"
files.push filename
kit = PDFKit.new(path)
pdf = kit.to_file("#{Rails.root}/public/invoices/#{filename}")
...
end
这是由PDFKit调用的标签方法:
def labels
@invoices = Invoice.find(params[:selected_invoices])
render :layout => 'labels_layout'
end
标签方法失败,这是后台发生的事情:
Processing by InvoicesController#labels as HTML
Invoice Load (0.3ms) SELECT "invoices".* FROM "invoices" WHERE "invoices"."id" = $1 LIMIT 1 [["id", nil]]
Completed 404 Not Found in 1ms (ActiveRecord: 0.3ms)
ActiveRecord::RecordNotFound (Couldn't find Invoice with 'id'=):
app/controllers/invoices_controller.rb:160:in `labels'
其余过程正常,我可以看到生成发票的PDF。我在这里缺少什么?
谢谢!
答案 0 :(得分:1)
尝试将path = labels_invoices_url
更改为path = labels_invoices_url(@invoices)
答案 1 :(得分:0)
我尝试以几种方式明确传递参数或变量,包括:
path = labels_invoices_url(@invoices)
和path = labels_invoices_url(params[:selected_invoices]
这两个都给了我类似的错误。我尝试了不同的策略,并在索引页面上创建了两个提交按钮:
<%= submit_tag "Print Selected Invoices" %> <%= submit_tag "Print Labels" %>
我利用每个按钮在参数中发送自己的提交,并使用if / else语句修改generate_multiple_pdfs
方法以检查params[:commit]
:
def generate_multiple_pdfs
if params[:commit] == "Print Labels"
@invoices = Invoice.find(params[:selected_invoices])
render :labels, :layout => 'labels_layout'
else
#do the invoice pdfs
end
end
这不会生成pdf格式的标签,而是需要两次点击而不是一次,但现在可以使用。
如果有人知道如何通过PDFKit传递变量或参数,就像我尝试的那样,我真的很感激他们的帮助。否则看起来我会在文档中挖掘,看看我错过了哪些基础知识。
谢谢!