read

If you add new versions to a CarrierWave uploader in Rails, change size or anything like that you'll need to reprocess images that have already been uploaded to look consistent with the new ones. The CarrierWave gem gives you a way to do this easily with recreate_versions!, but that's basically all they say in the documentation. The easiest way to do this is by creating a rake task and run it in your environments (Dev, production on Heroku, etc).

First of all let's create a new task with

$ rails g task carrierwave recreate_versions

Now move to ./lib/tasks/ and open your newly generated carrierwave.rake file which should look something like this:

namespace :carrierwave do
  desc "TODO"
  task recreate_versions: :environment do
  end
end

Now, there are two use cases with CarrierWave: the first, in which the uploader is mounted on your model, and the second one in which you use nested attributes for multiple images uploading. In the latter case you load the images through an array (i.e. Deal.deal_attachments[i]), but each image has an instance of his own as a DealAttachment, this means that you don't have to iterate through your parent model and then the attachments but you can do that on the attachment model itself:

namespace :carrierwave do
 desc "Recreate versions for CarrierWave"
  task recreate_versions: :environment do
    DealAttachment.all.where("image IS NOT NULL").each do |d|
        d.image.recreate_versions!
    end
  end
end

If your uploader is mounted on the parent model you can simply change DealAttachment with Deal and it will work just fine. Now you can save the file and run the task with

rake carrierwave:recreate_versions

Every time you make a change in your uploader you can just run this task again. I've done this on a Heroku production environment with around 50-60 images and didn't have any problem, but I don't take responsibilities with higher volume of images in case of overcharges or anything like that.

Blog Logo

Alessio Fanelli

I'm a full stack developer with a love for sports.


Published

Image

Alessio Fanelli

Stay Sharp.

Back to Overview