ruby-on-rails - Rails 6 ActiveStorage附加文件网址不起作用
问题描述
我有一个应用程序,用户可以在其中上传 PDF 文档,当上传 pdf 文档时(使用使用 ActiveStorage DirectUpload 的前端刺激控制器),然后我处理 PDF 以剥离内容以放入 Excel 电子表格。一切都上传到 s3 存储桶。
我的模型如下所示:
class Export < ApplicationRecord
has_one_attached :pdf
has_one_attached :spreadsheet
validates :pdf, attached: true, content_type: 'application/pdf'
def process_pdf!
self.pdf.open(tmpdir: "#{Rails.root}/tmp") do |file|
tmpfile = File.open(file.path)
file_name = File.basename(file.path).sub(".pdf", "")
op = PdfScraper.call(pdf_file: tmpfile, output_name: file_name)
attach_spreadsheet(file_name: file_name)
end
end
private
def attach_spreadsheet(file_name:)
self.spreadsheet.attach(
io: File.open("#{Rails.root}/tmp/#{file_name}.xlsx"),
filename: "#{file_name}.xlsx",
identify: false,
content_type: "application/vnd.ms-excel"
)
end
end
控制器如下所示:
class ExportsController < ApplicationController
def create
@export = Export.new(export_params)
@export.uuid = cookies[:visitor_uuid]
respond_to do |format|
if @export.save
@export.process_pdf!
flash[:notice] = "Success!"
format.html { redirect_to download_path }
else
flash[:error] = @export.errors
format.html { redirect_to root_path }
end
end
end
private
def export_params
params.require(:export).permit(:pdf)
end
end
当重定向发生回到 时download_path
,我会根据 cookie ID 找到导出,但是当我尝试检查(或查看)附加电子表格的下载 URL 时,我收到以下错误:
undefined method `persisted?' for nil:NilClass
视图看起来像:
<p>
<%= polymorphic_url(@export.spreadsheet) %>
</p>
我什至尝试过rails_blob_url(@export.spreadsheet)
,但它不起作用。如果我通过 rails 控制台查找 URL,它似乎可以工作。
解决方案
推荐阅读
- gradle - gradle 从 4 升级到 gradle 6.0 - 不支持替换可能已被其他插件使用的现有任务
- flutter - 如何获得 Uint8List 图像大小?
- java - DRYing String 分布在多个类中
- reactjs - 更新状态未反映在调度中
- postgresql - Postgres 容器无法启动
- powerbi - 优化从 Azure Cosmos DB 到 Power BI 的数据加载
- swiftui - 在 SwiftUI 1 中使用 LazyVStack
- api - 是否有仅发布根 URL 的 REST API 文档?
- java - Kafka 消费者和生产者在同一个 IntelliJ 项目中
- swift - How can I iterate through a specific JSON item in Swift