【问题标题】:Empty folders when file is deleted using CarrierWave使用 CarrierWave 删除文件时的空文件夹
【发布时间】:2011-11-03 12:01:16
【问题描述】:

当我使用 CarrierWave 和 Mongoid 删除上传的文件时,它会删除文件但保留空文件夹。

/files/:user_id/images/:file_id/ ['image.png', 'content_image.png', 'thumb_image.png']

我希望在删除文件时也删除 :file_id 文件夹。有没有办法做到这一点?

【问题讨论】:

    标签: ruby-on-rails-3.1 mongoid carrierwave


    【解决方案1】:

    我已经解决了这个问题:

      before_destroy :remember_id
      after_destroy :remove_id_directory
    
      protected
    
      def remember_id
        @id = id
      end
    
      def remove_id_directory
        FileUtils.remove_dir("#{Rails.root}/path/to/folder/#{@id}", :force => true)
      end
    

    【讨论】:

    • 你把这个放在哪里?在上传器中?还是在模型上?
    • after_destroy 似乎适合模型:undefined method 'after_destroy' for ImportUploader:Class
    • @user1055045 - 我们不需要两个回调,因为 after_destroy 仍然可以访问 id。
    • 小心!确保您告诉remove_dir 吹走的路径与您打算删除的任何内容相匹配。围绕 remove_dir 语句的额外 IF 语句不会受到伤害。 ;)
    • 哇,,, 它为我删除了所有文件.. 如果我只想删除特定文件怎么办?
    【解决方案2】:

    您可以运行每日 cron 作业来清除目录:

    cd /your/uploads/dir && find . -type d -empty -exec rmdir {} \;
    

    【讨论】:

    • 有什么反对的?我会选择这个解决方案。谢谢
    【解决方案3】:

    你也可以这样做:

    after_destroy :remove_file_directory
    
    
     def remove_file_directory
        path = File.expand_path(mount.store_path, mount.root)
        FileUtils.remove_dir(path, force: false)
     end
    

    mount 是你所挂载的_as 例如:如果你有mount_uploader :avatar, AvatarUploader 那么

     def remove_file_directory
        path = File.expand_path(avatar.store_path, avatar.root)
        FileUtils.remove_dir(path, force: false)
     end
    

    【讨论】:

    • 如果出于某种奇怪的原因路径是 / 怎么办?最好在 remove_dir 周围设置保护措施
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多