I am facing an embarrassing issue with paperclip. When calling destroy method of the associated model. the database record is deleted , but not the attachment files.
I have seen the rails server logs, and I see the log “Deleting attachments” only, without the logs for deleting the files.
I’m using filename interpolation to rename the uploaded files (see the code).
When I delete this interpolation (removing :path & :url from the model) I notice that destroy method is working correctly. So I am sure of the root cause : filename interpolation.
am I using interpolation in a wrong way? is it a known issue in paperclip?
:path => ":rails_root/public/system/:attachment/:id/:style/:normalized_photo_file_name.:extension",
:url =>
"/system/:attachment/:id/:style/:normalized_photo_file_name.:extension"
Paperclip.interpolates :normalized_photo_file_name do |attachment, style|
attachment.instance.normalized_photo_file_name
end
def normalized_photo_file_name
if @rnd.nil?
@rnd= SecureRandom.hex(4)
end
"photo_#{@rnd}"
end
Yes, you are. Interpolations are supposed to be reproductible, they should yield exactly the same value for every call for a specific controller and in your case you’re generating the random value on all calls.
When the object is destroyed, the interpolation will be called again, it will generate a different random value and it isn’t going to find this new file. If you really want to have this hex value, generate and store it in your model or instead of using a random use a hashing algorithm like a digest. Here’s how it would look like:
This guarantees the same value will be generated for all models and your destroy method is going to behave correctly.