gpt4 book ai didi

ruby-on-rails - 销毁时不会删除回形针附件

转载 作者:行者123 更新时间:2023-12-03 15:56:49 27 4
gpt4 key购买 nike

当模型被破坏时,使用 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

文章 Controller 中的销毁操作:
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

最佳答案

您需要在销毁附件之前将其"file"属性设置为 nil,以便从磁盘中删除上传的文件。

所以你的代码应该是这样的

文章 Controller 中的销毁操作:

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

关于ruby-on-rails - 销毁时不会删除回形针附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25174538/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com