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

时间:2015-06-11 14:09:59

标签: ruby-on-rails carrierwave cloudinary

我有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

使用它的上传器也使用了carrierwave:

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。所以,这意味着如果我在Image中有这样的文件:

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

然后这意味着我需要在AccountMediaContent中使用完全相同的文件,因此该文件的链接将是相同的。有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:0)

最佳解决方案是使用代表图像的新模型,然后将其链接到两个模型。

答案 1 :(得分:0)

好吧我的解决方案并不是很好,但无论如何。我所做的是编写了下载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 

希望它对某人有用。