【问题标题】:Passing params between multiple methods in Rails在 Rails 中的多个方法之间传递参数
【发布时间】:2016-04-18 03:57:25
【问题描述】:

我正在构建一个客户数据库/发票系统。当发票准备好使用 PDFKit 转换为可打印的 PDF 时,它们会通过包含复选框的表单从 Invoices 索引中选择,该复选框通过 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

labels 方法失败,这是后台发生的情况:

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。我在这里错过了什么?

谢谢!

【问题讨论】:

  • 你能说明你是如何称呼标签的吗?表格邮寄到哪里?
  • 标签被 pdfkit 调用,使用 labels_invoices_url 路由:path = labels_invoices_url 然后kit = PDFKit.new(path)。我不确定您在询问表单发布到的位置。
  • 您必须将参数显式传递给标签方法。参数哈希仅适用于您发布到的方法,所以我猜测表单 POST 到 generate_multiple_pdfs。

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

尝试将path = labels_invoices_url 更改为path = labels_invoices_url(@invoices)

【讨论】:

  • 谢谢,感谢您的回复。我已经尝试过了,但它仍然给了我同样的错误ActiveRecord::RecordNotFound (Couldn't find Invoice with 'id'=): app/controllers/invoices_controller.rb:160:in labels'` 我最终以不同的方式修复它。我会在几秒钟内发布。
【解决方案2】:

我尝试通过几种方式显式传递参数或变量,包括:

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 传递变量或参数,我将非常感谢他们的帮助。否则,我似乎会在文档中挖掘,看看我错过了哪些基础知识。

谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    相关资源
    最近更新 更多