I am using Paperclip with AWS in my rails app. 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. The issue is when I do .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:
# 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-
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. 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.
Another possible cause could have been missing permits for deleting files. Check the deletion directly over the ruby s3 sdk.