Ruby-on-rails 销毁记录时如何让载波删除文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6553392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:30:57  来源:igfitidea点击:

How to make carrierwave delete the file when destroying a record?

ruby-on-railsrubycarrierwave

提问by Oakland510

I'm using the carrierwave gem to upload files.

我正在使用carrierwave gem 上传文件。

I have built a system for users to flag images as inappropriate and for admins to remove the images. From what I can tell, calling destroy on the image will only remove the path name from the table.

我已经建立了一个系统,供用户将图像标记为不当,并供管理员删除图像。据我所知,对图像调用 destroy 只会从表中删除路径名。

Is there a way to have carrierwave actually remove the file itself? Or should rails automatically remove the file when I destroy the image path?

有没有办法让carrierwave实际删除文件本身?或者,当我销毁图像路径时,rails 应该自动删除文件吗?

回答by oconn

Like @mu_is_too_short said, you can use File#delete.

就像@mu_is_too_short 说的,你可以使用File#delete

Here's a code snippet you could use as a helper with a little tweaking in your rails app.

这是一个代码片段,您可以在 Rails 应用程序中稍作调整,将其用作助手。

def remove_file(file)
  File.delete(file)
end

or if you just have the filename stored in file

或者如果您只是将文件名存储在文件中

def remove_file(file)
  File.delete("./path/to/#{file}")
end

回答by basicxman

Not sure what CarrierWave offers for this, but you could use FileUtilsin the Ruby standard library with an ActiveRecord callback.

不确定 CarrierWave 为此提供什么,但您可以FileUtils在 Ruby 标准库中使用 ActiveRecord 回调。

For instance,

例如,

require 'FileUtils'
before_destroy :remove_hard_image

def remove_hard_image
  FileUtils.rm(path_to_image)
end

Sidenote: This code is from memory.

旁注:此代码来自内存。

回答by orion

If one wants to delete a file but does not want to specify the full filename you can use the below.

如果您想删除文件但不想指定完整的文件名,您可以使用以下命令。

Can also be used to delete many files or all files in a directory with a specific extension...

也可用于删除具有特定扩展名的目录中的许多文件或所有文件...

file = Rails.root.join("tmp", "foo*") 

or

或者

file = Rails.root.join("tmp", ".pdf")  


files = Dir.glob(file) #will build an array of the full filepath & filename(s)
files.each do |f|
  File.delete(f)
end