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

Oakland510 picture Oakland510 · Jul 1, 2011 · Viewed 71.4k times · Source

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?

Answer

oconn picture oconn · Feb 6, 2014

Like @mu_is_too_short said, you can use File#delete.

Here's a code snippet you could use as a helper with a little tweaking in your rails app.

def remove_file(file)
  File.delete(file)
end

or if you just have the filename stored in file

def remove_file(file)
  File.delete("./path/to/#{file}")
end