保存前从活动存储附件中读取

Fra*_*ank 2 ruby ruby-on-rails rails-activestorage

我有用户上传 JSON 文件作为模型的一部分Preset,非常标准的 Active Storage 东西。有点不寻常的一件事(我想,鉴于我无法使其工作)是我想从上传的 JSON 文件中获取数据并使用它来注释Preset记录,如下所示:

class Preset < ApplicationRecord
    has_one_attached :hlx_file
    before_save :set_name

    def set_name
        file = JSON.parse(hlx_file.download)
        self.name = file['data']['name']
    end
end
Run Code Online (Sandbox Code Playgroud)

当我调用 hlx_file.download 我得到ActiveStorage::FileNotFoundError: ActiveStorage::FileNotFoundError.

ahm*_*eij 7

Rails 6 将文件上传到存储的时间更改为在实际保存记录期间。

这意味着 before_save 或验证不能以常规方式访问文件。

如果您需要访问新上传的文件,您可以获得如下文件引用:

record.attachment_changes['<attributename>'].attachable
Run Code Online (Sandbox Code Playgroud)

这将是要附加文件的临时文件。

注意:以上是一个未记录的内部 api,可能会发生变化(https://github.com/rails/rails/pull/37005