当模型被销毁时,使用Paperclip(v4.2.0)保存的附件不会从磁盘中删除,是否有其他人遇到此问题?一切都按预期工作,但文件不会从磁盘中删除。任何帮助或想法都将受到超级赞赏!
型号:
class Attachment < ActiveRecord::Base
belongs_to :article
has_attached_file :file, { :preserve_files => "false" }
do_not_validate_attachment_file_type :file
end
class Article < ActiveRecord::Base
belongs_to :topic
belongs_to :subtopic
belongs_to :author
has_many :attachments, :dependent => :destroy
accepts_nested_attributes_for :attachments, allow_destroy: true, reject_if: lambda { |a| a[:file].blank? }
validates :topic_id, presence: true
validates :title, presence: true, length: { maximum: 16 }
validates :subtitle, length: { maximum: 20 }
validates :content, presence: true
end
销毁文章控制器中的操作:
def destroy
@article = Article.find(params[:id])
begin
# first delete the attachments from disk
@article.attachments.each do |a|
a.file.destroy
end
@article.destroy
rescue
flash[:danger] = "Unable to delete article"
else
flash[:success] = "Article deleted"
end
redirect_to admin_articles_url
end
答案 0 :(得分:2)
您需要设置附件&#39;文件&#39;在销毁之前将属性设置为nil,以便从磁盘中删除上传的文件。
所以你的代码应该是这样的
销毁文章控制器中的操作:
def destroy
@article = Article.find(params[:id])
begin
# first delete the attachments from disk
@article.attachments.each do |a|
a.file = nil
a.save
end
@article.destroy
rescue
flash[:danger] = "Unable to delete article"
else
flash[:success] = "Article deleted"
end
redirect_to admin_articles_url
end
答案 1 :(得分:1)
尝试将preserve_files选项添加到“false”字符串
has_attached_file :file, :preserve_files => "false"
答案 2 :(得分:1)
想出来:
def destroy
self.transaction do
self.images.destroy_all
super
end
end
self.images
是带附件的记录集合。
最重要的是self.transaction do ...
,因为当出于任何原因super
(原始destroy
)失败时,它不会从hdd中删除文件。它一直等到COMMIT
答案 3 :(得分:0)
尝试这样的事情:
def destroy
@article = Article.find(params[:id])
@article.attachments.destroy
@article.destroy
respond_to do |format|
format.html { redirect_to admin_articles_url }
end
end
@article = Article.find(params[:id])
会找到您要删除的文章。
@article.attachments
将收集与该特定文章相关的所有附件
注意:所有附件销毁后必须销毁@article
。如果您在@article.destroy
之前写下@article.attachments.destroy
,则会在未找到@article的情况下发出错误。
正如您在Article
模型has_many :attachments, :dependent => :destroy
中提到的那样
那么我认为不需要写@article.attachments.destroy
来销毁@article
它会删除与之相关的所有附件。
答案 4 :(得分:0)
您还可以使用 before_destroy 回调
例如
class User < ActiveRecord::Base
before_destroy :delete_image
has_attached_file :image,
path: "/attachments/:class/:attachment/:style/:filename"
validates_attachment_content_type :image, content_type: \Aimage\/.*\z/
private
def delete_image
self.image = nil
self.save
end
end
然后,只要销毁模型类的实例,就会首先删除附件。