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
I did in in payment.rb model after I save my Payment object.
Get an error:
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
I have a view payments/show.pdf.erb
of course.
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:
Instead of polluting my model with all this, I might create a service object something like this:
Then in the model you could do this:
This work for me: