重命名路径时回形针或 Google 云存储问题

Paperclip or Google Cloud Storage issue when renaming paths

我有一个带 Paperclip 的 Rails 应用程序,我使用 Google 云存储。到目前为止,一切都很好。

为了避免开发和生产使用同一个存储,我决定根据环境将默认的Paperclip路径更改为另一个。这样每个环境都有自己的目录。然后我不断地将旧图像从默认回形针路径移动到新路径。

问题是现在旧图片会出现 404,而我上传的任何新图片都可以正常工作。有什么办法可以解决这个问题吗?

这是之前的设置:

module MyApp
  class Application < Rails::Application

  config.paperclip_defaults = {
    storage: :fog,
    fog_public: true,
    fog_directory: 'myapp-01',
    fog_credentials: {
      google_storage_access_key_id: ENV['GOOGLE_STORAGE_ID'],
      google_storage_secret_access_key: ENV['GOOGLE_STORAGE_SECRET'],
      provider: 'Google'
    }
  }
}

我使用以下设置覆盖默认设置:

    path: ":rails_env/:class/:attachment/:id_partition/:style/:filename",
    url:  "/:rails_root/:class/:attachment/:id_partition/:style/:filename"

我的猜测是用新路径更新 Paperclip 配置并将所有图像移动到新目录是不够的。您还需要更新旧记录... 如果您想知道,旧记录指向 root/images/?123456789.

你猜对了。更改配置是不够的,您需要移动文件。这个,最好留给 rake 任务或后台工作。我有一些 S3 的代码,但它应该让您了解如何为 Google:

实现它
  def old_key(image, file_name_field)
    # Previous `:path`: '/:class/:attachment/:id/:style/:filename'
    klass = self.class.to_s.pluralize.downcase
    attachment = image.pluralize
    "#{klass}/#{attachment}/#{id}/original/#{send(file_name_field)}"
  end

  def re_path(image)
    file_name_field = "#{image}_file_name"
    return if send(file_name_field).blank?

    old_object = bucket.object(old_key(image, file_name_field))
    return unless old_object.exists?

    Rails.logger.warn "Re-saving image attachment #{self.class}/#{id}"
    send "#{image}=", URI.parse(old_object.public_url)
    save
  end

我基本上是使用自己的插值构建旧路径,在 S3 中找到对象(因此 key/object 行话)并从 S3 重新下载每个图像。小心这一点,因为如果某人 Google 允许,您可能会因下载而不仅仅是移动而产生额外费用。

然后我就在每个对象的每个图像上调用了这个方法:

Object.each do { |o| o.re_path(:logo); o.re_path(:background); }