ruby-on-rails Rails -为S3迁移重新保存所有模型

z18hc3ub  于 2023-05-02  发布在  Ruby
关注(0)|答案(2)|浏览(167)

rails 6.1.3.2aws-sdk-s3 gem
我目前在生产环境中有一个rails应用程序,它使用ActiveStorage将图像数据附加到 Package 器Image模型。它目前使用本地策略将图像保存到磁盘,我正在将其迁移到S3。我没有使用回形针或类似的东西。
我成功地设置了它。目前,它被设置为主要使用本地,并将S3作为镜像,以便在迁移过程中可以写入两个位置。然而,文档说,它只会在创建和更新记录时将新图像保存到S3。我想“重新保存”生产中的所有模型,以强制迁移。有人知道怎么做吗?

dsekswqp

dsekswqp1#

Looks like it was already answered!
如果你碰巧像我一样只能访问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?
vxf3dgd4

vxf3dgd42#

因为你已经在轨道6上了。1、可以使用#mirror_later。它将使后台工作进程入队以镜像到已配置的服务。

ActiveStorage::Blob.find_each do |blob|
  blob.mirror_later
end

参考: www.example.com

相关问题