55

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?

Kimmo Lehto
  • 5,910
  • 1
  • 23
  • 32
Oakland510
  • 1,073
  • 2
  • 12
  • 20

3 Answers3

102

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
oconn
  • 2,112
  • 2
  • 18
  • 15
  • 7
    what is the difference between File#delete and FileUtils.rm? – Tall Paul Feb 20 '15 at 21:34
  • 5
    in 2.2.2 it looks like `File.delete` will take filename(s) as individual arguments and will return an Integer of the number of files removed. It will also raise an exception on any error. `FileUtils.rm` takes a list , or string, of filename(s) and can also be passed options like `:force => true` which will not raise an exception. – oconn Aug 27 '15 at 14:14
62

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.

basicxman
  • 2,095
  • 14
  • 21
  • 29
    There's also [`File#delete`](http://ruby-doc.org/core/classes/File.html#M000018) in the core clases. – mu is too short Jul 01 '11 at 22:14
  • 3
    `require 'fileutils'` if you don't want to get all kinds of warnings about constants. – Samuel Jun 11 '15 at 14:11
  • Using a gem for something straight forward like this, esp. which the stdlib offers this seem unnecessary. +1 to File#delete – yekta Jan 13 '16 at 18:46
  • @yekta [`fileutils.rb` is part of the Ruby Standard Library](https://github.com/ruby/ruby/blob/trunk/lib/fileutils.rb). – Dennis Jul 14 '16 at 23:01
  • Oh, huh. IIRC I was looking in the docs and didn't see it. Thanks for point that out. – yekta Jul 16 '16 at 02:00
1

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
orion
  • 504
  • 1
  • 5
  • 17