如何测试模型中是否使用 Active Storage 发送了新文件?

How to test if a new file is sent with Active Storage in the model?

在我的 Rails 模型中,我有这段代码可以在上传时强制更改文件名:

before_save :set_filename  
  def set_filename
    if file.attached?
      self.file.blob.update(filename: "#{new_file_name()}.#{self.file.blob.content_type.split('/')[1]}")
    end
  end

问题是即使没有在表单中发送新文件(编辑时),文件名也会更改。

我的附件简单命名为文件:

# active storage
  has_one_attached :file

上传时如何真正测试是否附加了新文件?

谢谢,

编辑:更多说明

我有一个带有 file_field 的表格。 当我添加或修改表单的对象时,我想测试是否通过表单发送了一个新文件。

我的模型名为Image,附件名为file。

class Image
  has_one_attached :file
end

每次通过表单发送新文件时,我都想更改文件名,当然不是 file_field 保持为空。

您可以使用 new_record? 来检查 file 是否是新的,即:

  def set_filename
    if file.attached? && file.new_record?
      self.file.blob.update(filename: "#{new_file_name()}.#{self.file.blob.content_type.split('/')[1]}")
    end
  end

或者,使用 before_create 而不是 before_save,以便 set_name 仅在上传新文件时运行。

已更新

有趣的是,ActiveStorage 在模型挂钩之外处理 blob 更改。显然,它现在甚至不支持验证。无法验证 blob 是否已更改,因为它的状态不会在任何地方持久化。如果您查看 rails 日志,请注意 rails 在添加新 blob 后立即清除旧 blob。

我能想到的几个选项:

1.Update 控制器中的文件名 例如:

original_name = params[:file].original_name
params[:file].original_name = # your logic goes here

2.Store 父模型中的 blob 文件名并在 before_save.

中进行比较
  def set_filename
    if file.attached? && file.blob.filename != self.old_filename
      self.file.blob.update(filename: "#{new_file_name()}.#{self.file.blob.content_type.split('/')[1]}")
    end
  end

None 这些解决方案是理想的,但希望它们能给您一些想法。