Search code examples
ruby-on-railsrubypaperclip

Rails Paperclip delete local attachment if upload successful


I have the code below to save my local file to AWS S3. It uploads my file to S3 correctly, but then my local file is not deleted. Now I've filled disk space completely. How can I ask paperclip to remove local file after it has uploaded it?

class JobArtifact < ActiveRecord::Base
  attr_reader :remote_url
  has_attached_file :file, path: 'tmp/:id/:fingerprint.:extension'

  do_not_validate_attachment_file_type :file

  def remote_url=(url)
    self.file = URI.parse(url_value)

    @remote_url = url
  end
end

It is called this way:

@filename = "#{Rails.root}/tmp/values.csv"
JobArtifact.create(file: File.open(@filename))

Solution

  • Since you know the path of the file you can just do something like this after it's uploaded to s3 -

    def remove_file
      File.delete(@filename) if File.exist?(@filename)
    end