PDF发票和Rails中的Mailer

时间:2019-03-18 16:55:03

标签: ruby-on-rails actionmailer prawn

我尝试学习Rails,但被困住了。 我有用户,工作,发票和客户模型。我正在用Prawn创建发票和Pdf发票。 Pdf发票未保存(我不想保存pdf,只想在浏览器中查看pdf),现在我想要一个通过电子邮件发送pdf发票的按钮。我有发票显示视图​​2按钮,一个用于查看Pdf,另一个用于通过电子邮件发送pdf。

= link_to 'View PDF', invoice_path(@invoice, format: "pdf")
\|
= link_to "Send Email", invoice_mail_path(current_user, @invoice), class: "btn btn-xs btn-primary"

我有:

invoice_mailer.rb

default from: "example@yahoo.com"

  def invoice_mail(invoice, user, job)
    @invoice = invoice
    @user = user
    @job = job
    attachments["#{(@invoice.invoice_number)}.pdf"] = InvoicePdf.new(@invoice, view_context).render

    mail(to: 'example@yahoo.com',
         subject: "A new invoice from xxx")
  end

invoices_controller.rb

def invoice_mail

# @invoice = Invoice.last
@invoice = Invoice.new(@invoice)
@user = current_user
@job = current_user.jobs

InvoiceMailer.invoice_mail(@invoice, @user, @job).deliver_now

flash[:notice] = "Invoice has been sent."
redirect_to invoices_path 
end

routes.rb

get :invoice_mail, to: 'invoices#invoice_mail', as: :invoice_mail

如果我有,在def invoice_mail的invoices_controller中

@invoice = Invoice.last

正在工作,正在发送带有pdf附件的电子邮件,但正在获取最后一张发票。如果我有

@invoice = Invoice.new(@invoice)

给我错误

要获取当前发票,我需要什么而不是@invoice = Invoice.last?还是我做错了什么?

当我点击“发送电子邮件”按钮时,我在终端上有一个

Started GET "/invoice_mail.16-446cd684-c756-4ea3-a820-17756f44098d" for 127.0.0.1 at 2019-03-22 11:07:30 -0400
Processing by InvoicesController#invoice_mail as 
User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 2], ["LIMIT", 1]]
↳ /Users/ovi_tsb/.rvm/gems/ruby-2.4.1/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
Completed 404 Not Found in 2ms (ActiveRecord: 0.4ms)



ActiveRecord::RecordNotFound (Couldn't find Invoice without an ID):

app/controllers/invoices_controller.rb:124:in `invoice_mail'

1 个答案:

答案 0 :(得分:0)

@invoice = Invoice.new(@invoice)

在您的控制器中,这没有任何意义。您要为@invoice的值分配一个Invoice.new(@invoice)的零值,该值等于Invoice.new(nil)。那不应该引发任何错误,但是这样做确实没有任何意义。

大概,您要做的是根据 ID 查找发票。就像:

@invoice = Invoice.find(params[:id])

这意味着您的请求应包含一个:id参数。如果没有,则需要包括它。但我相信应该有它:

= link_to "Send Email", invoice_mail_path(current_user, @invoice), 
                        class: "btn btn-xs btn-primary"

第二,上面的link_to不需要包含current_usercurrent_user是对Rails通过用户会话获取的User的引用。换句话说,默认情况下它将存在于您的控制器中。因此,不要理会它:

= link_to "Send Email", invoice_mail_path(@invoice), 
                         class: "btn btn-xs btn-primary"

让我们使用以下新信息来清理控制器:

def invoice_mail
  @invoice = Invoice.find(params[:id]) # :id should be the invoice ID
  @jobs = current_user.jobs

  InvoiceMailer.invoice_mail(@invoice, current_user, @jobs).deliver_now
  flash[:notice] = "Invoice has been sent."
  redirect_to invoices_path 
end