Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming existing CarrierWave files

How do you rename existing images with CarrierWave? (This question is close but not really the same: Renaming uploaded files with Carrierwave) For example, if model.image.url is foo-bar-jpg how can I rename both the file and and the corresponding database field to foo-bar.jpg?

model.image.recreate_versions! will create new files but in the database it doesn't change the model's image field.

like image 351
chrismealy Avatar asked Dec 28 '11 01:12

chrismealy


1 Answers

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.

like image 178
Rhb123 Avatar answered Sep 27 '22 19:09

Rhb123