ruby-on-rails - 如何从 Paperclip 文件动态设置 preserve_files 选项?

标签 ruby-on-rails paperclip

在我的项目中,我将 Paperclip 与 Paranoia 一起使用gem(为了软删除某些模型)。在这个模型中,我同时使用了两个 gem:

class Material < ActiveRecord::Base
    has_attached_file :material, preserve_files: true

    acts_as_paranoid

    validates_attachment :material, presence: true
end

Paranoia gem 提供了一种硬删除对象的方法:really_destroy!方法。但是,当我调用此方法时,对象被删除但文件被保留。我什么是删除文件太。例子:
@material_a.destroy # soft-delete the object and preserve the file
@material_b.really_destroy! # hard-delete the object and delete the file

有什么办法可以动态设置 Paperclip preserve_files 选项吗?

最佳答案

似乎您无法动态设置 :preserve_files 选项,但还有另一种方法可以做您想做的事。

Paperclip 通过首先设置要删除的路径队列来删除附件,然后在保存对象时删除它们。如果同一对象有多种样式(例如,图像文件的大小不同),则对象可以有多个要删除的路径。如果您调用#destroy 或#clear(不带参数),它将调用#queue_all_for_delete,它会检查是否设置了:preserve_files。但是如果你用要删除的样式列表调用#clear,它会调用#queue_some_for_delete,它不会检查:preserve_files。

所以,我们只需要向#clear 提供所有样式的列表:

all_styles = @material_b.attachment.styles.keys.map { |key|
    @material_b.attachment.styles[key].name
} << :original
@material_b.attachment.clear(*all_styles)
@material_b.save
@material_b.really_destroy!

关于ruby-on-rails - 如何从 Paperclip 文件动态设置 preserve_files 选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27062924/

相关文章:

amazon-s3 - 亚马逊 aws-s3 访问被拒绝错误

ajax - 如何异步上传图片

ruby-on-rails - 为 Rails 4 : why should you keep user profile data on a separate table to the Devise User models table 设计

ruby-on-rails - bundler ,Rails3 : how to avoid git check of edge gems in :test group during deploying?

ruby-on-rails - 嵌套连接查询,只有第三张表的最后一行

html - 向 Rails 中的 simple_form 提交按钮添加图标

ruby-on-rails - 回形针/乘客 NotIdentifiedByImageMagickError :

ruby-on-rails - Ubuntu 18.04 服务器(Rails 6.0)上的 `secret_key_base` 环境缺少 'production',尝试了多个主题

ruby-on-rails - Rails 4 - Paperclip - 使用 DATA URI 上传图像

ruby-on-rails - 如何在回形针中使用原始图像网址