使用 carrierwave 时如何使 2 个上传器指向 1 个 cloudinary 文件?

How can I make 2 uploader to point to 1 cloudinary file when using carrierwave?

我有 Image 型号:

class Image < ActiveRecord::Base
  mount_uploader :file, ModuleImageUploader
end

上传图片我使用 carrierwave + cloudinary:

class ModuleImageUploader < CarrierWave::Uploader::Base
  include Cloudinary::CarrierWave

  process :resize_to_limit => [700, 700]

  version :mini do
    process :resize_and_pad => [50, 50, '#ffffff']
  end

  version :thumb do
    process :resize_and_pad => [100, 100, '#ffffff']
  end

  def public_id
    return SecureRandom.uuid
  end
end

我创建了新模型 AccountMediaContent:

class AccountMediaContent < ActiveRecord::Base
  mount_uploader :image, AccountMediaContentImageUploader
end

它的上传器也使用载波:

class AccountMediaContentImageUploader < CarrierWave::Uploader::Base
  include Cloudinary::CarrierWave

  process :resize_to_limit => [700, 700]

  version :mini do
    process :resize_and_pad => [50, 50, '#ffffff']
  end

  version :thumb do
    process :resize_and_pad => [100, 100, '#ffffff']
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end
end

现在我需要将图像从 Image 传输到 AccountMediaContent 的方法。所以,这意味着如果我在图像中有这样的文件:

http://res.cloudinary.com/isdfldg/image/upload/v1344344359/4adcda41-49c0-4b01-9f3e-6b3e817d0e4e.jpg

那么这意味着我需要在 AccountMediaContent 中使用完全相同的文件,因此文件的 link 将是相同的。有什么办法可以实现吗?

对此的最佳解决方案是拥有一个代表图像的新模型,然后 link 将其应用于两个模型。

好吧,我的解决方案不是很好,但无论如何。我所做的是我编写了下载 Cloudinary 中已有图像 Image 的脚本,然后将它们附加到新模型 AccountMediaContent.

我的任务是这样的:

Image.find_in_batches do |imgs_in_batch|
  imgs_in_batch.each do |img|

    # Downloading image to tmp folder (works on heroku too)
    file_format = img.file.format
    img_url = img.file.url
    tmp_file = "#{Rails.root.join('tmp')}/tmp-img.#{file_format}"

    File.open(tmp_file, 'wb') do |fo|
      fo.write open(img_url).read
    end

    # Creating AccountMediaContent with old image (it'll be uploaded to cloudinary.
    AccountMediaContent.create(image: File.open(tmp_file))

    FileUtils.rm(tmp_file)
  end
end 

希望对大家有用。