Rya*_*yan 5 ruby-on-rails rails-activestorage
我正在使用 Active Storage 在 Rails 5.2 项目中存储文件。我有文件保存到 S3,但它们使用随机字符串文件名保存并直接保存到存储桶的根目录。我不介意随机文件名(我实际上更喜欢我的用例),但希望将不同的附件组织到存储桶中的文件夹中。
我的模型使用has_one_attached :file. 例如,我想指定将所有这些文件存储/downloads在 S3内的一个文件夹中。我找不到有关如何设置这些路径的任何文档。
has_one_attached :file, folder: '/downloads'如果可能的话,类似的东西会很棒......
最终的解决方案是添加一个初始化程序。您可以根据环境变量或您的以下内容添加前缀Rails.env:
# config/initializer/active_storage.rb
Rails.configuration.to_prepare do
ActiveStorage::Blob.class_eval do
before_create :generate_key_with_prefix
def generate_key_with_prefix
self.key = if prefix
File.join prefix, self.class.generate_unique_secure_token
else
self.class.generate_unique_secure_token
end
end
def prefix
ENV["SPACES_ROOT_FOLDER"]
end
end
end
Run Code Online (Sandbox Code Playgroud)
它与此完美配合。其他人建议使用Shrine。
感谢这个伟大的解决方法: https://dev.to/drnic/how-to-isolate-your-rails-blobs-in-subfolders-1n0c
| 归档时间: |
|
| 查看次数: |
7161 次 |
| 最近记录: |