为了在 S3 上拥有自定义文件名,您应该同时更新blob.key
S3 上的名称和名称。
blob.key
主动存储使用远程图像路径和名称在 S3 上上传图像。
对于我的使用,我只使用猴子补丁更改了“图像变体”的名称,该补丁允许通过以下方式生成key
终止filename
:
config/initializers/active_storate_variant.rb
:
ActiveStorage::Variant.class_eval do
def key
"variants/#{blob.key}/#{Digest::SHA256.hexdigest(variation.key)}/#{filename}"
end
end
因此,当我需要图像变体的公共 url 时,我只需调用image.url('400x400')
这就是我的图像模型的自定义方式:
class Image < ApplicationRecord
belongs_to :imageable, polymorphic: true
has_one_attached :picture
SIZES = { '400x400' => '400x400' }
def url(size)
return "https://placehold.it/#{size}" unless picture.attached?
'https://my_s3_subdomain.amazonaws.com/' +
picture.variant(resize: SIZES[size]).processed.key
end
...
end
如果有人有更好的方法来做到这一点,我会很高兴看到它:)