简体   繁体   English

回形针在销毁时不会从 S3 中删除图像

[英]Paperclip not deleting images from S3 on destroy

I am using Paperclip with AWS in my rails app.我在 Rails 应用程序中使用带有 AWS 的 Paperclip。 I have a model that holds the image:我有一个保存图像的模型:

class PaperclipFile < ActiveRecord::Base
  before_validation :parse_image

  belongs_to :attachment

  attr_accessor :base64_attachment

  has_attached_file :image, preserve_files: false
  validates_attachment :image, presence: true 
  do_not_validate_attachment_file_type :image

  private
    def parse_image
      return unless base64_attachment
      image = Paperclip.io_adapters.for(base64_attachment) 
      image.original_filename = "img_#{SecureRandom.urlsafe_base64}.jpg" 
    end
end

Basically I can pass an image in base64 and it processes and stores it correctly on S3.基本上我可以在 base64 中传递图像,它可以在 S3 上正确处理和存储它。 The issue is when I do .destroy问题是当我做 .destroy

p = PaperclipFile.first
p.destroy

After that the record is gone from the DB but the file is not destroyed from the bucket.之后,记录从数据库中消失,但文件不会从存储桶中销毁。 I don't get any errors so it doesn't look like it's trying at all.我没有收到任何错误,所以它看起来根本没有尝试。

The output is:输出是:

2.4.0 :005 > PaperclipFile.first.destroy
  PaperclipFile Load (0.8ms)  SELECT  "paperclip_files".* FROM "paperclip_files" ORDER BY "paperclip_files"."id" ASC LIMIT $1  [["LIMIT", 1]]
   (0.2ms)  BEGIN
  SQL (0.7ms)  DELETE FROM "paperclip_files" WHERE "paperclip_files"."id" = $1  [["id", 2]]
   (4.1ms)  COMMIT
 => #<PaperclipFile id: 2, attachment_id: 2, created_at: "2017-04-03 04:02:11", updated_at: "2017-04-03 04:02:11", image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil> 
2.4.0 :006 > 

For the record I use Ruby 2.4, Rails 5.0.2 and as for the gems they look like this:作为记录,我使用 Ruby 2.4、Rails 5.0.2,至于 gem,它们看起来像这样:

# Attachments
gem 'paperclip'
gem 'aws-sdk', '~> 2.3'

Thanks!谢谢!

There is nothing wrong with the code that you have written.您编写的代码没有任何问题。

If you want to remove the image from S3 as well just make the following changes-如果您还想从 S3 中删除图像,只需进行以下更改-

p = PaperclipFile.first
p.destroy # Removes the attachment from DB
p.clear # Deletes the attachment from S3
p.save # To save the model.

Default preserve_files set to false.默认preserve_files 设置为false。 Try removing option as follow.尝试删除选项如下。

has_attached_file :image

I had no issues with destroy, but I used delete_all , which does not triggers the callbacks, and had the same effect you have seen.我对 destroy 没有任何问题,但我使用了delete_all ,它不会触发回调,并且具有您所看到的相同效果。

Another possible cause could have been missing permits for deleting files.另一个可能的原因可能是缺少删除文件的许可。 Check the deletion directly over the ruby s3 sdk.直接通过 ruby​​ s3 sdk 检查删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM