如何将本地存储(活动存储)迁移到Google云存储

时间:2020-09-17 13:05:04

标签: ruby-on-rails google-cloud-platform google-cloud-storage

我正尝试在Google Cloud上迁移我的Rails应用。 我已经将活动存储与在GCS上创建的存储桶相连接。 我已经在存储桶中上传了文件夹“ storage”,但应用程序中的所有图像都出现404错误。

我如何正确迁移GCS中的本地存储文件夹?

谢谢你的建议

2 个答案:

答案 0 :(得分:0)

我将编写一个迁移并遍历所有具有附件的模型,并将当前图像与目录中的本地文件“重新分配”,以便将其与GCS同步。也可以看看Active Storage guide

答案 1 :(得分:0)

该问题与this非常相似,如该线程所述:

DiskService使用与Google上的云存储服务不同的文件夹结构。

DiskService将密钥的第一个字符的一部分用作文件夹。云服务仅使用密钥并将所有变体放在单独的文件夹中。

您可以创建一个rake任务,将文件复制到云存储中,例如:

namespace :active_storage do
  desc "Migrates active storage local files to cloud"
    task migrate_local_to_cloud: :environment do
      raise 'Missing storage_config param' if !ENV.has_key?('storage_config')

      require 'yaml'
      require 'erb'
      require 'google/cloud/storage'

      config_file = Pathname.new(Rails.root.join('config/storage.yml'))
      configs = YAML.load(ERB.new(config_file.read).result) || {}
      config = configs[ENV['storage_config']]

      client = Google::Cloud.storage(config['project'], config['credentials'])
      bucket = client.bucket(config.fetch('bucket'))

      ActiveStorage::Blob.find_each do |blob|
        key = blob.key
        folder = [key[0..1], key[2..3]].join('/')
        file_path = Rails.root.join('storage', folder.to_s, key)
        file = File.open(file_path, 'rb')
        md5 = Digest::MD5.base64digest(file.read)
        bucket.create_file(file, key, content_type: blob.content_type, md5: md5)
        file.close
        puts key
      end
    end
  end

执行为:rails active_storage:migrate_local_to_cloud storage_config = google。

您可以在here上找到有用的文档。