ruby-on-rails 如何在Amazon S3中定制Rails 5.2 ActiveStorage附件的路径?

bz4sfanl  于 2023-02-14  发布在  Ruby
关注(0)|答案(2)|浏览(165)

添加附件时,例如

has_one_attached :resume_attachment

保存的文件最后会出现在S3存储桶的顶层。2我怎样才能将它们添加到子目录中呢?3例如,我以前的回形针配置可以按型号名称对目录进行分类。

hc8w905p

hc8w905p1#

不能。对于has_one_attachedhas_many_attached宏,此时只有一个可能的选项,即:dependent。https://github.com/rails/rails/blob/master/activestorage/lib/active_storage/attached/macros.rb#L30
看(也许你有下投的原因,但它是关于“直接”上传所以...):How to specify a prefix when uploading to S3 using activestorage's direct upload?。响应来自Active Storage的主要维护者。

0yg35tkg

0yg35tkg2#

使用before_validation钩子在S3上设置所需的密钥,并在S3上设置内容处置对象属性所需的文件名。
附件模型上的keyfilename属性将传递到ActiveStorage S3 gem,并转换为S3密钥+内容处置对象属性。

class MyCoolItem < ApplicationRecord
  has_one_attached :preview_image
  has_one_attached :download_asset

  before_validation :set_correct_attachment_filenames

  def preview_image_path
    # This key has to be unique across all assets. Fingerprint it yourself.
    "/previews/#{item_id}/your/unique/path/on/s3.jpg"
  end

  def download_asset_path
    # This key has to be unique across all assets. Fingerprint it yourself.
    "/downloads/#{item_id}/your/unique/path/on/s3.jpg"
  end
  
  def download_asset_filename
    "my-friendly-filename-#{item_id}.jpg"
  end

  def set_correct_attachment_filenames
    # Set the location on S3 for new uploads:
    preview_image.key = preview_image_path if preview_image.new_record?
    download_asset.key = download_asset_path if download_asset.new_record?

    # Set the content disposition header of the object on S3:
    download_asset.filename = download_asset_filename if download_asset.new_record?
  end
end

相关问题