ruby-on-rails - Rails - 为 S3 迁移重新保存所有模型
问题描述
rails 6.1.3.2
aws-sdk-s3 gem
我目前有一个生产中的 Rails 应用程序,它使用 ActiveStorage 将图像数据附加到包装图像模型。它目前正在使用本地策略将图像保存到磁盘,我正在将其迁移到 S3。我没有使用回形针或类似的东西。
我成功设置了它。目前它被设置为主要使用本地并将 S3 作为镜像,以便我可以在迁移期间写入两个地方。但是文档说它只会在创建和更新记录时将新图像保存到 S3。我想“重新保存”生产中的所有模型以强制迁移发生。有谁知道如何做到这一点?
解决方案
如果您碰巧像我一样只能访问 Rails 控制台,那么这个解决方案非常有效。如果您将此代码复制粘贴到控制台中,它将开始生成 S3 上传的输出。在其中 5k 之后,我完成了。非常感谢Tayden的解决方案。
all_services = [ActiveStorage::Blob.service.primary, *ActiveStorage::Blob.service.mirrors]
# Iterate through each blob
ActiveStorage::Blob.all.each do |blob|
# Select services where file exists
services = all_services.select { |file| file.exist? blob.key }
# Skip blob if file doesn't exist anywhere
next unless services.present?
# Select services where file doesn't exist
mirrors = all_services - services
# Open the local file (if one exists)
local_file = File.open(services.find{ |service| service.is_a? ActiveStorage::Service::DiskService }.path_for blob.key) if services.select{ |service| service.is_a? ActiveStorage::Service::DiskService }.any?
# Upload local file to mirrors (if one exists)
mirrors.each do |mirror|
mirror.upload blob.key, local_file, checksum: blob.checksum
end if local_file.present?
# If no local file exists then download a remote file and upload it to the mirrors (thanks @Rystraum)
services.first.open blob.key, checksum: blob.checksum do |temp_file|
mirrors.each do |mirror|
mirror.upload blob.key, temp_file, checksum: blob.checksum
end
end unless local_file.present?
推荐阅读
- android - 为什么在我替换 Android 中的当前片段后我的 ViewModel 仍然存在?
- flutter - 如何在 Flutter 中存储关键数据?
- c# - 与 U-Net 共享游戏设置
- django - 告诉我如何为 Django 用户发布密码更改?
- mp3 - 在 MP3 文件中查找
- excel - 按路径和名称错误引用工作簿:下标超出范围
- php - 接收海量数据的最佳实践 [laravel Restfult API]
- dolphindb - 在 dolphindb 中,我有两个独立的集群。如何在这两个集群之间传输分布式数据库
- c++ - C ++:无法检测到变量的变化,人工“易失性”互斥锁不起作用
- postgresql - 搜索字符串并在表中插入值