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

Ruby on-RailsRubyCarrierwave

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

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.

Solution 3 - Ruby on-Rails

If one wants to delete a file but does not want to specify the full filename you can use the below.

Can also be used to delete many files or all files in a directory with a specific extension...

file = Rails.root.join("tmp", "foo*") 

or

file = Rails.root.join("tmp", ".pdf")  

files = Dir.glob(file) #will build an array of the full filepath & filename(s)
files.each do |f|
  File.delete(f)
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOakland510View Question on Stackoverflow
Solution 1 - Ruby on-RailsoconnView Answer on Stackoverflow
Solution 2 - Ruby on-RailsbasicxmanView Answer on Stackoverflow
Solution 3 - Ruby on-RailsorionView Answer on Stackoverflow