I try to convert rails views into pdf with the gem wicked_pdf. But when I do a render_to_string like this
ActionController::Base.new.render_to_string(template: "templates/pdf_meteo.html.erb", locals: {communaute_meteo_id: id}, layout: 'pdf')
Methods like user_path
don't work and return undefined method error... (note that the page work properly if I render it in html)
If someone can help me !
Unfortunately, using render_to_string
will not give you access to Rails URL helpers. One workaround is to include them directly in the locals
that you pass into the PDF template using something like url: Rails.application.routes.url_helpers
:
ActionController::Base.new.render_to_string(
template: "templates/pdf_meteo.html.erb",
locals: {url: Rails.application.routes.url_helpers, communaute_meteo_id: id}
layout: 'pdf'
)
And then inside of your PDF template you would call them with:
url.user_path
Keep in mind that by default the _path
URL helpers will be relative, and not absolute paths. You can instead use the _url
version of the helpers and set the host
for them in a few different ways. You can configure them globally for your entire app:
# config/environments/development.rb
Rails.application.routes.default_url_options[:host] = 'www.mysite.com'
or set them individually on each helper inside of your PDF template:
url.user_url(host: 'www.mysite.com')
Hope that gets you what you need!