5

I need to be able to delete files from S3 that are stored by users, such as profile photos. Just calling @user.logo.destroy doesn't seem to do the trick - I get [paperclip] Saving attachments. in the logs and the file stays right there in the S3 bucket.

How can the file itself be removed?

sscirrus
  • 55,407
  • 41
  • 135
  • 228

2 Answers2

3

This are the methods from Paperclip that can be used to remove the attachments:

# Clears out the attachment. Has the same effect as previously assigning
# nil to the attachment. Does NOT save. If you wish to clear AND save,
# use #destroy.
def clear(*styles_to_clear)
  if styles_to_clear.any?
    queue_some_for_delete(*styles_to_clear)
  else
    queue_all_for_delete
    @queued_for_write  = {}
    @errors            = {}
  end
end

# Destroys the attachment. Has the same effect as previously assigning
# nil to the attachment *and saving*. This is permanent. If you wish to
# wipe out the existing attachment but not save, use #clear.
def destroy
  clear
  save
end

So you see, destroy only removes the attachment if no error occurs. I have tried it with my own setup against S3 so I know that destroy works.

Could the problem in your case possible be that you have any validations that cancels the save? I.e validates_attachment_presence or something similar?

I think one way to find out would be to try @user.logo.destroy and then check the content of @user.errors to see if it reports any error messages.

imtk
  • 1,510
  • 4
  • 18
  • 31
DanneManne
  • 21,107
  • 5
  • 57
  • 58
  • I did as you listed here, can you please see my question here: http://stackoverflow.com/questions/14144454/how-to-hook-for-destroy-of-a-model-that-belongs-to-another-model – simo Jan 04 '13 at 08:26
1

This seems like an answer to your question, although I don't totally understand their distinction between destroy and clear (I don't know which model has_attached_file, page or image):

Rails Paperclip how to delete attachment?

Community
  • 1
  • 1
John Bachir
  • 22,495
  • 29
  • 154
  • 227