有没有办法在Rails中保存Active Storege创建的具有自定义文件名的文件



我正在尝试创建一个表单,用户可以在其中使用活动存储上传视频。但是,当文件存储到存储文件夹中时,默认情况下它们使用 ID 作为文件名。有什么办法,我可以创建具有自定义名称的文件,例如用户的电子邮件作为文件名。因此,我可以轻松区分哪些文件是由谁上传的?

您不必担心文件名,但请尝试在上传文件时设置文件名的这段代码:

class Model < ApplicationRecord
  after_create :set_filename
  def set_filename
    if self.active_storage_object.attached?
      self.active_storage_object.blob.update(filename: "desired_filename.#{self.active_storage_object.filename.extension}")
    end
  end
end

来源: https://medium.com/fiatinsight/how-to-change-a-filename-in-rails-active-storage-f3e4f26f427e

阅读有关 AS 存储模型的更多信息:

https://bloggie.io/@kinopyo/7-practical-tips-for-activestorage-on-rails-5-2

请注意文件名字段在active_storage_blobs表中的显示方式。

最新更新