首页 > 解决方案 > 活动存储 - 初始化程序中的错误解决方法不起作用

问题描述

我正在尝试解决 Active Storage 中的一个已知问题,其中存储文件的 MIME 类型设置不正确,无法覆盖它。

https://github.com/rails/rails/issues/32632

这已经在masterRails 的分支中得到解决,但是它似乎还没有发布(项目目前使用 5.2.0)。因此,我正在尝试使用问题中提供的评论之一来解决该问题:

在新的初始化程序 ( \config\initializers\active_record_fix.rb) 中:

Rails.application.config.after_initialize do
  # Defeat the ActiveStorage MIME type detection.
  ActiveStorage::Blob.class_eval do
    def extract_content_type(io)
      return content_type if content_type
      Marcel::MimeType.for io, name: filename.to_s, declared_type: content_type
    end
  end
end

我正在使用delayed_jobs. 初始化程序似乎没有被调用。我已经重新启动了服务器。我正在本地运行项目,heroku local用于处理后台作业。

这是存储文件的代码:

file.attach(io: File.open(temp_zip_path), filename: 'Download.zip', content_type: 'application/zip')

任何想法为什么上面的代码不起作用?Active Storage 喜欢随机确定此 ZIP 文件为 PDF 并将内容类型保存为application\pdf. 不相关,尝试手动覆盖content_type后附加不起作用:

file.content_type = 'application/zip'
file.save # No errors, but record doesn't update the content_type

标签: ruby-on-railsrails-activestorage

解决方案


尝试Rails.application.config.to_prepare代替after_initialize 初始化事件。

更多信息 :


推荐阅读