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

前端 未结 4 793
南旧
南旧 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:16

    I'd try the following steps:

    1. Change the storage in the uploaders to :fog or what ever you want to use
    2. Write a migration like rails g migration MigrateFiles to let carrierwave get the current files, process them and upload them to the cloud.

    If your model looks like this:

    class Video
      mount_uploader :attachment, VideoUploader
    end
    

    The migration would look like this:

    @videos = Video.all
    @videos.each do |video|
      video.remote_attachment_url = video.attachment_url
      video.save
    end
    

    If you execute this migration the following should happen:

    Carrierwave downloads each image because you specified a remote url for the attachment(the current location, like http://test.com/images/1.jpg) and saves it to the cloud because you changed that in the uploader.

    Edit:

    Since San pointed out this will not work directly you should maybe create an extra column first, run a migration to copy the current attachment_urls from all the videos into that column, change the uploader after that and run the above migration using the copied urls in that new column. With another migration just delete the column again. Not that clean and easy but done in some minutes.

提交回复
热议问题