我可以在before_save回调中的模型动作中生成它之后立即下载pdf文件吗?

问题描述:

在模型中,我生成一个pdf文件,若付款方法是发票:我可以在before_save回调中的模型动作中生成它之后立即下载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文件。我需要的是能够在发电后立即下载文件。试过我要下载的文件,generate_pdf方法pdf块结束后添加此权:

send_data(filename: pdf, type: 'public/pdf') 

但现在看来,这send_data只能在控制器中。那么,有没有办法从模型中以某种方式下载它?谢谢你。

您无法从模型发送文件。控制器使模型数据可用于响应。控制器应该能够从模型中获取生成的文件并将其发送给用户。

它可以这样实现:

# 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