首页 > 解决方案 > 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,它似乎可以工作。

标签: ruby-on-railsrails-activestorage

解决方案


推荐阅读