2017-04-03 12 views
0

我在我的rails應用程序中使用AWS回形針。我有保持所述圖像的模型:Paperclip不會從S3上刪除圖像湮滅

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並作爲寶石,他們是這樣的:

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

謝謝!

回答

0

您編寫的代碼沒有任何問題。

如果你想刪除從S3圖像也只是使設置爲false以下changes-

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

明確不是p的函數。也許你的意思是p.image.clear/p.image.destroy?我也嘗試過那些沒有任何運氣 – mrk

+0

只是嘗試保存對象後,你做p.image.destroy/p.image.clear –

+0

感謝您的建議,但迄今沒有喜悅 – mrk

0

默認preserve_files。嘗試刪除選項如下。

has_attached_file :image 
+0

謝謝。不幸的是,我已經嘗試了兩種方法:nothing和preserve_files:false,效果相同 – mrk

+0

讓我們試試更多的方法。 '''p.image = nil p.save p.destroy''' – scs

+0

我試過了,但沒有幫助。原來它與使用偏執狂有關。我從任何地方移除了偏執狂,它很有效。我必須正確連線,但至少我知道.destroy現在刪除圖像。謝謝! – mrk