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

67 views Asked by At

I have Image model:

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

To upload image I use 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

I created new model AccountMediaContent:

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

with it's uploader which also uses 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

Right now I need to the way to transfer the image from Image to AccountMediaContent. So, that means if I had such file in Image:

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

Then it means that I need the exact same file in AccountMediaContent so the link to the file will be the same. Is there any way to achieve this?

2

There are 2 answers

0
ExiRe On BEST ANSWER

Ok my solution is not really good but anyway. What I did is I wrote the script which downloaded already existing images Image in Cloudinary and then I attached them to new model AccountMediaContent.

My task looks like this:

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 

Hope it'll be useful for someone.

0
Itay Taragano On

The optimal solution for this would be to have a new model which represents the image, and then link it to both models.