How can I reorganize an existing folder hierarchy with CarrierWave?

后端 未结 1 1912
天涯浪人
天涯浪人 2021-02-05 21:45

I am trying to move files around my S3 bucket using CarrierWave to reorganize the folder structure.

I came to an existing Rails application where all images

相关标签:
1条回答
  • 2021-02-05 22:25

    WARNING: This is untested, so please don't use on production before testing it out.

    Here's the thing, once you change the contents of 'store_dir', all your old uploads will become missing. You know this already. Interacting with S3 directly seems like the most obvious way of solving this, since carrierwave doesn't have a move function.

    One thing that might work, would be to re-'store' your uploads and change the 'store_dir' path in the 'before :store' callback.

    In your uploader:

    #Use the old uploads directory so carriewave knows where the original upload is
    def store_dir
      'uploads'
    end
    
    before :store, :swap_out_store_dir
    
    def swap_out_store_dir
      self.class_eval do
        def store_dir
          "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
        end
      end
    end
    

    And then run a script like this:

    MyClass.all.each do |image|
      image.image.cache! #create a local cache so that store! has something to store
      image.image.store!
    end
    

    After this, verify that the files have been copied to the correct locations. You'll then have to delete the old upload files. Also, remove the one time use uploader code above and replace it with your new store_dir path:

    def store_dir
      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id} "
    end
    

    I haven't tested this out, so I can't guarantee it will work. Please use test data first to see if it works and comment here if you've had any success.

    0 讨论(0)
提交回复
热议问题