gpt4 book ai didi

ruby-on-rails - Rails 4 wicked_pdf 在模型中的服务器上保存 pdf

转载 作者:行者123 更新时间:2023-12-03 16:12:56 28 4
gpt4 key购买 nike

我正在尝试将 pdf 保存在这样的模型中:

def save_invoice
pdf = WickedPdf.new.pdf_from_string(
render_to_string(:pdf => "invoice",:template => 'documents/show.pdf.erb')
)
save_path = Rails.root.join('pdfs','filename.pdf')
File.open(save_path, 'wb') do |file|
file << pdf
end
end

保存 Payment 对象后,我在 payment.rb 模型中进行了操作。

得到一个错误:
undefined method `render_to_string' for <Payment object>

早些时候在 Controller 中没有问题
def show
@user = @payment.user
#sprawdza czy faktura nalezy do danego uzytkownika
# [nie mozna podejrzec po wpisaniu id dowolnej faktury]
if current_user != @user
flash[:error] = I18n.t 'errors.invoice_forbidden'
redirect_to '/' and return
end
respond_to do |format|
format.html do
render :layout => false
end
format.pdf do
render :pdf => "invoice",:template => "payments/show"
end
end
end

我有意见 payments/show.pdf.erb当然。

最佳答案

Rails 模型没有方法 render_to_string .
渲染 View 不是模型的责任。

如果您绝对需要在模型中执行此操作,则可以执行以下操作:

def save_invoice
# instantiate an ActionView object
view = ActionView::Base.new(ActionController::Base.view_paths, {})
# include helpers and routes
view.extend(ApplicationHelper)
view.extend(Rails.application.routes.url_helpers)
pdf = WickedPdf.new.pdf_from_string(
view.render_to_string(
:pdf => "invoice",
:template => 'documents/show.pdf.erb',
:locals => { '@invoice' => @invoice }
)
)
save_path = Rails.root.join('pdfs','filename.pdf')
File.open(save_path, 'wb') do |file|
file << pdf
end
end

我可能会创建一个类似这样的服务对象,而不是用所有这些来污染我的模型:
class InvoicePdfGenerator
def initialize(invoice)
@invoice = invoice
@view = ActionView::Base.new(ActionController::Base.view_paths, {})
@view.extend(ApplicationHelper)
@view.extend(Rails.application.routes.url_helpers)
@save_path = Rails.root.join('pdfs','filename.pdf')
end

def save
File.open(@save_path, 'wb') do |file|
file << rendered_pdf
end
end

private

def rendered_pdf
WickedPdf.new.pdf_from_string(
rendered_view
)
end

def rendered_view
@view.render_to_string(
:pdf => "invoice",
:template => 'documents/show.pdf.erb',
:locals => { '@invoice' => @invoice }
)
end
end

然后在模型中你可以这样做:
def save_invoice
InvoicePdfGenerator.new(self).save
end

关于ruby-on-rails - Rails 4 wicked_pdf 在模型中的服务器上保存 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25032224/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com