Renaming Uploaded Files with Carrierwave

Changing the file name that we upload using carrierwave in rails

You can rename file during upload:

def filename
"#{model.invoice_number}.#{file.extension}" if original_filename.present?
end

Renaming existing CarrierWave files

I used the technique described here: How to assign a remote file to Carrierwave?

This may not be the best way to go, but it worked for me. My remote file just happened to be the old file name/path.

First, I changed the Carrierwave uploader to have the new file name style I wanted. Then I wrote a rake task to iterate through the records and update the files like this:

model.remote_image_url = old_image_url
model.save!

This will upload the existing file again, setting the name/path based on your updated Uploader (and recreate all versions). I haven't tackled the issue of cleaning up the old files yet, I'm not sure how this will work if your store_dir is the same (mine changed as well).

Make sure to test thoroughly on a few records before running through your full table, its easy to make a mess of things. Be aware that changing your store_dir will break all of your lookups for existing files.



Related Topics



Leave a reply



Submit