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:

post.rb

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

  after_destroy :delete_empty_upload_directory

  private
    def delete_empty_upload_directory
      FileUtils.rm_rf(Rails.root.join('path', 'to', 'your', 'uploads', self.id.to_s)) if self.image
    end
end

Simple, nice, and easy.

November 11, 2015