ruby-on-rails - 获取'未定义的方法`view_paths ='#你的意思?在 Rails 中使用 PDFKit 的 view_paths 错误
问题描述
我正在使用 PDFKit(连同 Gem render_anywhere 和 wkhtmltopdf-binary)来创建一个按钮,用于在 Rails 中从 HTML 创建 PDF。我遵循了几个都使用“发票”作为示例的教程。我的应用程序使用“审计”。我以为我已经完成了所有事情,但是在 ActionView::LookupContext object: 上出现错误undefined method 'view_paths=' for #<ActionView::LookupContext:0x00007fdb191d6cc0> Did you mean? view_path
。它与错误的路径和在 Rails 中使用服务类有关,但似乎找不到解决方案。这是我制作PDF的代码:
PDFKit 宝石:https ://github.com/pdfkit/pdfkit
我正在使用的教程:https ://code.tutsplus.com/tutorials/generating-pdfs-from-html-with-rails--cms-22918
downloads_controller
: _
class DownloadsController < ApplicationController
def show
respond_to do |format|
format.pdf { send_audit_pdf }
end
end
private
def audit_pdf
audit = params[:incoming]
AuditPdf.new(audit)
end
def send_audit_pdf
send_file audit_pdf.to_pdf,
filename: audit_pdf.filename,
type: "application/pdf",
disposition: "inline"
end
end
Download
型号:
require "render_anywhere"
class Download
include RenderAnywhere
def initialize(audit)
@audit = audit
end
def to_pdf
kit = PDFKit.new(as_html, page_size: 'A4')
kit.to_file("#{Rails.root}/public/audit.pdf")
end
def filename
"audit #{audit.id}.pdf"
end
private
attr_reader :audit
def as_html
render template: "audits/pdf", layout: "audit_pdf", locals: { audit: audit }
end
end
我的views/layout/audit_pdf.html.erb
样子是这样的:
<!DOCTYPE html>
<html>
<head>
<title>Audit PDF</title>
<style>
<%= Rails.application.assets.find_asset('audit.pdf').to_s %>
</style>
</head>
<body>
<%= yield %>
</body>
</html>
解决方案
由于您仅使用 rails api,因此您正面临这个问题。
你需要改变
def as_html
render template: "audits/pdf", layout: "audit_pdf", locals: { audit: audit }
end
至:
def pdf_html
ActionController::Base.new.render_to_string(template: 'audits/pdf.html.erb', layout: 'audit_pdf.erb')
end
推荐阅读
- javascript - React js在多个图像文件上传中的问题
- javascript - 如何避免不断调用api?
- flutter - 使用 NestedScrollView 如果正文仍然适合屏幕,我如何阻止正文在 headerSliverBuilder 下滚动
- discord.js - Discord.js v13 邀请跟踪器
- system-verilog - System Verilog:初始时每个实例的随机化
- spring-boot - 如何使用spring boot将excel数据加载到neo4j中?
- python - 如果列的标题包含“价格”,则 Python/Pandas 格式化列的值
- continuous-integration - 在 GitHub Action 中调用可重用工作流时,秘密插值在调用者工作流中出现语法错误
- mysql - 从 Sequelize 和 Node.Js 中的引用表中获取数据
- http - 如何在 HTTP 请求中正确使用缓存控制标头