ruby-on-railsrubycarrierwave

How to make carrierwave delete the file when destroying a record?


I'm using the carrierwave gem to upload files.

I have built a system for users to flag images as inappropriate and for admins to remove the images. From what I can tell, calling destroy on the image will only remove the path name from the table.

Is there a way to have carrierwave actually remove the file itself? Or should rails automatically remove the file when I destroy the image path?


Solution

  • Not sure what CarrierWave offers for this, but you could use FileUtils in the Ruby standard library with an ActiveRecord callback.

    For instance,

    require 'FileUtils'
    before_destroy :remove_hard_image
    
    def remove_hard_image
      FileUtils.rm(path_to_image)
    end
    

    Sidenote: This code is from memory.