在模型中,如果付款方式为发票:
,我会生成pdf文件class Order < ApplicationRecord
require 'prawn'
after_save :generate_pdf
def generate_pdf
if payment_method.name == 'Invoice'
pdf = Prawn::Document.generate("public/pdf/invoice_#{SecureRandom.hex}_#{user.name}_№#{id}.pdf",
page_size: [200, 500],
page_layout: :landscape,
margin: 10) do |pdf|
pdf.text_box 'A test text', at: [0, 170]
end
end
end
end
此代码在public/pdf
文件夹中生成pdf文件。我需要的是能够在下一代下载文件。我尝试下载该文件,在pdf
方法的generate_pdf
块结束后立即添加此文件:
send_data(filename: pdf, type: 'public/pdf')
但似乎send_data
仅适用于控制器。那么,有没有办法从模型中以某种方式下载它?谢谢。
答案 0 :(得分:1)
您无法从模型发送文件。控制器使模型数据可用于响应。控制器应该能够从模型中获取生成的文件并将其发送给用户。
可以这样实现:
# controller
class OrdersController < ApplicationController
def create
# ...
@order.save
send_data(@order.pdf.render, type: 'application/pdf')
end
end
# model
require 'prawn'
class Order < ApplicationRecord
attr_accessor :pdf
after_save :generate_pdf
def generate_pdf
if payment_method.name == 'Invoice'
pdf = Prawn::Document.generate("public/pdf/invoice_#{SecureRandom.hex}_#{user.name}_№#{id}.pdf",
page_size: [200, 500],
page_layout: :landscape,
margin: 10) do |pdf|
pdf.text_box 'A test text', at: [0, 170]
self.pdf = pdf
end
end
end
end