简体   繁体   English

回形针故事附件未删除

[英]paperclip destory attachment not deleted

I am facing an embarrassing issue with paperclip. 回形针面临一个令人尴尬的问题。 When calling destroy method of the associated model. 调用关联模型的destroy方法时。 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. 我已经看到了Rails服务器日志,并且只看到了“ 删除附件 ”日志,而没有用于删除文件的日志。

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. 当我删除该插值(从模型中删除:path&:url)时,我注意到destroy方法可以正常工作。 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: 看起来像这样:

#put this somewhere
require 'digest/md5'

def normalized_photo_file_name
    "photo_#{Digest::MD5.hexdigest(self.id.to_s)}" 
end

This guarantees the same value will be generated for all models and your destroy method is going to behave correctly. 这样可以确保为所有模型生成相同的值,并且您的destroy方法将正确运行。

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

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