How can I migrate CarrierWave files to a new storage mechanism?

前端 未结 4 787
南旧
南旧 2021-02-06 02:31

I have a Ruby on Rails site with models using CarrierWave for file handling, currently using local storage. I want to start using cloud storage and I need to migrate existing lo

4条回答
  •  生来不讨喜
    2021-02-06 03:08

    When we use Heroku, most of people suggest to use cloudinary. Free and simple setup. My case is when we use cloudinary service and need move into aws S3 for some reasons.

    This is what i did with the uploader:

    class AvatarUploader < CarrierWave::Uploader::Base
    
      def self.set_storage
        if ENV['UPLOADER_SERVICE'] == 'aws'
          :fog
        else
          nil
        end
      end
    
      if ENV['UPLOADER_SERVICE'] == 'aws'
         include CarrierWave::MiniMagick
      else
         include Cloudinary::CarrierWave
      end
    
      storage set_storage
    end
    

    also, setup the rake task:

    task :migrate_cloudinary_to_aws do
        profile_image_old_url = []
        Profile.where("picture IS NOT NULL").each do |profile_image|
          profile_image_old_url << profile_image
        end
    
       ENV['UPLOADER_SERVICE'] = 'aws'
       load("#{Rails.root}/app/uploaders/avatar_uploader.rb")
    
       Profile.where("picture IS NOT NULL OR cover IS NOT NULL").each do |profile_image|
         old_profile_image = profile_image_old_url.detect { |image| image.id == profile_image.id }
         profile_image.remote_picture_url = old_profile_image.picture.url
         profile_image.save
       end
    end
    

    The trick is how to change the uploader provider by env variable. Good luck!

提交回复
热议问题