如何在Amazon S3中删除文件?使用Paperclip。

5

我需要能够删除用户存储在S3上的文件,例如个人资料照片。仅仅调用@user.logo.destroy似乎行不通 - 我在日志中看到[paperclip] Saving attachments.,但文件仍然保留在S3存储桶中。

如何删除文件本身?

2个回答

3
以下是可以用于删除附件的Paperclip方法:
# 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

所以你可以看到,destroy只有在没有错误发生时才会删除附件。我已经尝试过我的设置与S3对抗,所以我知道destroy是有效的。

在你的情况下可能的问题是你有任何取消保存的验证吗?例如validates_attachment_presence或类似的内容?

我认为找出一种方法是尝试@user.logo.destroy,然后检查@user.errors的内容,看它是否报告任何错误消息。


我按照您在这里列出的做法做了,您能否请看一下我的问题:https://dev59.com/eGzXa4cB1Zd3GeqPXcVT - simo

1

这似乎是对你问题的答案,尽管我不完全理解他们在destroy和clear之间的区别(我不知道哪个模型有_attached_file,页面还是图像):

Rails Paperclip如何删除附件?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接