Rails 4 wicked_pdf在模型中的服务器上保存pdf [英] Rails 4 wicked_pdf saving pdf on server in model
本文介绍了Rails 4 wicked_pdf在模型中的服务器上保存pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将pdf文件保存在这样的模型中:
I'm trying to save pdf in model like this:
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.rb模型中进行了操作.
I did in in payment.rb model after I save my Payment object.
出现错误:
undefined method `render_to_string' for <Payment object>
以前在控制器中做到了这一点
Earlier did it in controller without problem
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
.
呈现视图不是模型的责任.
Rails models doesn't have the method render_to_string
.
It is not the responsibility of the model to render views.
如果您绝对需要在模型中执行此操作,则可以执行以下操作:
If you absolutely need to do it in the model, you can do this:
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
我可以创建一个类似于以下内容的服务对象,而不是用这一切来污染我的模型:
Instead of polluting my model with all this, I might create a service object something like this:
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
然后在模型中可以执行以下操作:
Then in the model you could do this:
def save_invoice
InvoicePdfGenerator.new(self).save
end
这篇关于Rails 4 wicked_pdf在模型中的服务器上保存pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文