Rails views helper don't seems to work with render_to_string

空扰寡人 提交于 2019-12-24 06:28:13

问题


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 !


回答1:


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!




回答2:


Simplest way is to use regular rails rendering flow - with view file your_action_name.pdf.erb, trick is in overriding formats for partials:

<%= render partial:"some_partial", formats:[:html] %>

Also you can run render_to_string in context of your controller to have helpers (because ActionController::Base knows nothing about your app)



来源:https://stackoverflow.com/questions/58646135/rails-views-helper-dont-seems-to-work-with-render-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!