【问题标题】:Using Multiple Rails ActiveStorage Services使用多个 Rails ActiveStorage 服务
【发布时间】:2018-10-29 07:18:28
【问题描述】:

我正在使用 ActiveStorage 上传 PDF 和图像。由于一些隐私问题,PDF 需要存储在本地,而图像需要使用 Amazon S3 存储。但是,ActiveStorage 似乎只支持为每个环境设置一种服务类型(除非您使用镜像功能,在这种情况下它不能满足我的需要)

有没有办法在同一环境中使用不同的服务配置?例如,如果模型 has_one_attached pdf 它使用本地服务:

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

如果另一个型号 has_one_attached image 它使用亚马逊服务:

amazon:
  service: S3
  access_key_id: ""
  secret_access_key: ""

【问题讨论】:

    标签: ruby-on-rails amazon-s3 rails-activestorage shrine


    【解决方案1】:

    抱歉,Active Storage 恐怕不支持这个。

    【讨论】:

    • 有一个开放的拉取请求,看起来它很快就会被合并,但不幸的是,不适用于 Rails 6.0.0 版本github.com/rails/rails/pull/34935
    • 从 10 月 1 日开始合并,所以 Rails 6.1 应该有它
    【解决方案2】:

    ActiveStorage 很棒,但如果您需要每个环境中的多种服务类型,它目前不适合您(正如上面提到的 George Claghorn)。如果您需要其他选项,我使用Shrine 解决了这个问题。

    诀窍是在初始化程序中设置多个“商店”:

    # config/initializers/shrine.rb
    
    Shrine.storages = {
      cache: Shrine::Storage::FileSystem.new('storage', prefix: 'uploads/cache'),
      pdf_files: Shrine::Storage::FileSystem.new('storage', prefix: 'uploads'),
      images: Shrine::Storage::S3.new(**s3_options)
    }
    

    然后在 each 上传器(连接到给定模型)中使用default_storage 插件。请注意,除非您在 both 上传器中指定 default_storage,否则它不会起作用:

    class PdfFileUploader < Shrine
      plugin :default_storage, cache: :cache, store: :pdf_files
    end
    
    class ImageFileUploader < Shrine
      plugin :default_storage, cache: :cache, store: :images
    end
    

    【讨论】:

      【解决方案3】:

      Rails 6.1 现在支持这一点。

      根据this article,您可以指定service 用于每个attached

      class MyModel < ApplicationRecord
        has_one_attached :private_document, service: :disk
        has_one_attached :public_document,  service: :s3
      end
      

      【讨论】:

      • 现在,RAILS 6.1 发布后 - 似乎不支持多个 has_one_attached 语句!我收到错误消息:无法配置服务
      • 这似乎对我有用。您在config/storage.yml 中的服务配置是否正确?
      猜你喜欢
      • 1970-01-01
      • 2020-04-04
      • 2019-05-10
      • 2019-07-24
      • 1970-01-01
      • 2019-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多