chrismealy
chrismealy

Reputation: 4950

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.

Upvotes: 7

Views: 3815

Answers (3)

ryaz
ryaz

Reputation: 336

Found this, it seems like outdated, but maybe helps someone: https://github.com/stvkoch/carrierwave_single_store

Upvotes: 0

Rhb123
Rhb123

Reputation: 118

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.

Upvotes: 2

Simpleton
Simpleton

Reputation: 6415

The locomotive branch of Carrierwave seems to have rename support - the specific file is here.

There is file rename support in the main when you convert file types, but no rename support:

"This should help with situations where a file has multiple versions,
and at least one of the versions is of a different format than the master version."

Upvotes: 2

Related Questions