【问题标题】:Paperclip not deleting images from S3 on destroy回形针不会在销毁时从 S3 中删除图像
【发布时间】:2017-08-27 20:18:08
【问题描述】:

我在我的 rails 应用程序中使用带有 AWS 的 Paperclip。我有一个保存图像的模型:

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

基本上我可以在 base64 中传递一个图像,它会在 S3 上正确处理和存储它。问题是当我做 .destroy

p = PaperclipFile.first
p.destroy

之后,记录从数据库中消失,但文件并未从存储桶中销毁。我没有收到任何错误,所以它看起来根本不像在尝试。

输出是:

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 > 

为了记录,我使用 Ruby 2.4、Rails 5.0.2 以及它们看起来像这样的 gem:

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

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby amazon-s3 paperclip ruby-on-rails-5


    【解决方案1】:

    你写的代码没有问题。

    如果您还想从 S3 中删除图像,只需进行以下更改-

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

    【讨论】:

    • clear 不是 p 的函数。也许你的意思是 p.image.clear / p.image.destroy?我也试过那些没有运气的人
    • 在执行 p.image.destroy / p.image.clear 后尝试保存对象
    【解决方案2】:

    默认的 preserve_files 设置为 false。尝试删除选项如下。

    has_attached_file :image
    

    【讨论】:

    • 谢谢。不幸的是,我已经尝试了 nothing 和 preserve_files: false 具有相同的效果
    • 让我们尝试另一种方法。 p.image = nil p.save p.destroy
    • 我试过了,但没有帮助。原来这与使用偏执狂有关。我从任何地方都消除了偏执狂,它起作用了。我必须正确连接它,但至少我知道 .destroy 现在确实删除了图像。谢谢!
    【解决方案3】:

    我对销毁没有任何问题,但我使用了delete_all,它不会触发回调,并且效果与您看到的相同。

    另一个可能的原因是缺少删除文件的许可。 直接通过 ruby​​ s3 sdk 检查删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多