Clean up empty upload directories created by Carrierwave

Carrierwave doesn't clean up empty directories when you delete a record with an existing upload. It deletes the file, but not the containing directory. That is a task you can handle with an ActiveRecord callback.

Let say there is a model called 'Post' that you can attach an image to. The code would look like the following:


class Post < ActiveRecord::Base
  mount_uploadeder :image, ImageUploader

  after_destroy :delete_empty_upload_directory

    def delete_empty_upload_directory
      FileUtils.rm_rf(Rails.root.join('path', 'to', 'your', 'uploads', if self.image

Simple, nice, and easy.

November 11, 2015