首页 文章

使用邪恶的pdf gem时Rails中的双重渲染错误

提问于
浏览
0

在我的rails应用程序中,我正在创建一个API,接受来自其他设备的订单详细信息并生成pdf,然后将其上传到AWS . 我正在使用wicked_pdf gem生成pdf和aws-sdk以将数据上传到Aws . 控制器代码如下 .

def order_invoice
  response = Hash.new
  result = Hash.new
  if params[:order] && params[:order][:txnid] && 
     params[:no_of_copies] && params[:order][:total_amount]!= 0
    @order = params[:order]
              ...
    @no_of_copies = params[:no_of_copies]
    invoice = create_pdf
    response['result'] = invoice
    response.merge! ApiStatusList::OK
  else
    response.merge! ApiStatusList::INVALID_REQUEST
  end 
  render :json => response
end

def create_pdf
  pdf = WickedPdf.new.pdf_from_string(
          render_to_string(template: 'invoices/generate_invoice.pdf.erb'))

  send_data(pdf, filename: params[:order][:txnid] + ".pdf" ,
                 type: 'application/pdf',
                 disposition: 'attachment', print_media_type: true)
  save_path = Rails.root.join('pdfs', @order['txnid'] + ".pdf")
  File.open(save_path, 'wb') do |file|
    file << pdf
    filename = @order['txnid'] + ".pdf"
  end
  file_name =  @order['txnid'] + ".pdf"
  upload = Invoice.upload(save_path, file_name)
end

在生成和上传pdf时,我收到以下错误

AbstractController :: Api中的DoubleRenderError :: V0 :: InvoiceApiController#order_invoice在此操作中多次调用渲染和/或重定向 . 请注意,您只能调用渲染或重定向,每次操作最多一次 . 另请注意,重定向和呈现都不会终止操作的执行,因此如果要在重定向后退出操作,则需要执行类似“redirect_to(...)并返回”的操作 .

我需要将上传的pdf链接作为回复 . 我知道错误是因为在这里使用了两个渲染 . 但是,我不知道如何克服错误 . 任何人都可以帮我调整和更正代码 . 铁路和api的新手 .

1 回答

  • 1

    这是因为你渲染了两次repsonse:

    • 来自 send_data #create_pdf

    • 来自 render :json => response 在行动中

    UPD:

    经过讨论,我们来到了这一点 - 您的响应中不需要文件的内容,只需链接到AWS .

    所以,要解决此问题,请删除您的 send_file 电话:

    def create_pdf
      # render_to_string doesn`t mean "render response",
      # so it will not end up "double render"
      pdf = WickedPdf.new.pdf_from_string(
              render_to_string(template: 'invoices/generate_invoice.pdf.erb'))
    
      # send_file renders response to user, which you don't need
      # this was source of "double render" issue
      # so we can just remove it
      save_path = Rails.root.join('pdfs', @order['txnid'] + ".pdf")
      File.open(save_path, 'wb') do |file|
        file << pdf
        filename = @order['txnid'] + ".pdf"
      end
      file_name =  @order['txnid'] + ".pdf"
      upload = Invoice.upload(save_path, file_name)
    end
    

相关问题