Posted 21 days ago. Visible to the public. Repeats.

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 and cleans up any empty parent directories it can find.

Copy
class ExampleUploader < CarrierWave::Uploader::Base storage :file after :remove, :remove_empty_container_directory def store_dir # You implemented this in your uploaders already. end def remove_empty_container_directory(dir = store_dir) return unless Dir.empty?(dir) Dir.delete(dir) remove_empty_container_directory(File.dirname(dir)) end end

I suggest you also structure your file system for performance.

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
14 days ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more