Carrierwave: How to remove container directories when deleting a record

When deleting a record in your Rails app, Carrierwave automatically takes care of removing all associated files.
However, the file's container directory will not be removed automatically. If you delete records regularly, this may be an annoyance.

Here is a solution which was adapted from the Carrierwave GitHub wiki Archive and cleans up any empty parent directories it can find.

class ExampleUploader < CarrierWave::Uploader::Base

  storage :file
  after :remove, :remove_empty_container_directory
  def store_dir
    # You implemented this in your uploaders already.

  def remove_empty_container_directory(dir = store_dir)
    return unless Dir.empty?(dir)



I suggest you also structure your file system for performance.

Arne Hartherz 5 months ago
This website uses short-lived cookies to improve usability.
Accept or learn more