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

时间:2018-10-09 06:59:43

标签: ruby-on-rails rails-activestorage

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

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

此问题已在Rails的master分支中解决,但是它似乎尚未发布(项目当前正在使用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在后​​台作业中处理和存储一个zip文件。初始化程序似乎没有被调用。我已经重新启动服务器。我正在使用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

1 个答案:

答案 0 :(得分:1)

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

更多信息: