【发布时间】:2020-12-31 14:56:30
【问题描述】:
直到最近我扩展了 Rails 视图以在服务对象中生成 PDF:
view = ActionView::Base.new(ActionController::Base.view_paths, {})
view.extend(ApplicationHelper)
view.extend(Rails.application.routes.url_helpers)
WickedPdf.new.pdf_from_string(
view.render(
pdf: pdf_title,
template: template,
locals: { timesheet: timesheet },
print_media_type: true,
orientation: 'Portrait',
page_size: 'A4'
)
)
升级到 Rails 6.1 后,出现错误,因为这行发生了变化:
view = ActionView::Base.new(ActionController::Base.view_paths, {})
根据 Rails 源代码中的此提交,现在有第三个参数 controller 是必需的。
这个:
def initialize(lookup_context, assigns = {}, controller = nil)
改成这样:
def initialize(lookup_context, assigns, controller)
但我不确定在这种情况下controller 是什么以及我应该作为第三个参数提供什么,因为这都是从服务对象而不是控制器调用的。也只是添加一个nil 值作为第三个参数是行不通的,因为 PDF 在打开时是不可读的,所以我猜它不能正确扩展视图。
那么知道要提供什么值作为第三个参数吗?
【问题讨论】:
-
如果你有控制器,我认为调用
TimesheetsController.renderer.render(template:'timesheets/show)会给你html,但如果没有控制器,调用ApplicationController.renderer.render会工作吗?