2

我试图在保存到 ActiveStorage 之前重命名用户上传的文件,但我似乎没有找到任何文档来做到这一点。希望有人成功地做到了,并有代码示例可以分享。

谢谢你。

4

2 回答 2

4

你可以试试下面的方法

@message.image.attach(io: File.open('/path/to/file'), filename: 'file.pdf')

在官方ActiveStorage文档中,您可以找到更多示例

于 2018-05-10T18:16:50.890 回答
1

模型中的这种方法对我有用:

class Model < ApplicationRecord
has_one_attached :anything

  before_save do
    if self.anything.attached?
        ext = '.' + self.anything.blob.filename.extension
        self.anything.blob.update(filename: 'desired_file_name' + ext)
    end
  end
end
于 2021-01-13T18:57:53.080 回答