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
2条答案
按热度按时间hc8w905p1#
不能。对于
has_one_attached
,has_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的主要维护者。
0yg35tkg2#
使用
before_validation
钩子在S3上设置所需的密钥,并在S3上设置内容处置对象属性所需的文件名。附件模型上的
key
和filename
属性将传递到ActiveStorage S3 gem,并转换为S3密钥+内容处置对象属性。