在我的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时,我收到以下错误
Abstract Atroller :: Api中的DoubleRenderError :: V0 :: InvoiceApiController#order_invoice 在此操作中多次调用渲染和/或重定向。请注意,您只能调用渲染或重定向,每次操作最多一次。另请注意,重定向和渲染都不会终止操作的执行,因此如果要在重定向后退出操作,则需要执行类似&#34; redirect_to(...)之类的操作并返回&#34;。
我需要将上传的pdf链接作为回复。我知道错误是因为在这里使用了两个渲染。但是,我不知道如何克服错误。任何人都可以帮我调整和更正代码。铁路和api的新手。
答案 0 :(得分: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