我有用户上传 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
当我调用 hlx_file.download 我得到
ActiveStorage::FileNotFoundError: ActiveStorage::FileNotFoundError
.
最佳答案
Rails 6 将文件上传到存储的时间更改为在实际保存记录期间。
这意味着 before_save 或验证不能以常规方式访问文件。
如果您需要访问新上传的文件,您可以获得如下文件引用:
record.attachment_changes['<attributename>'].attachable
这将是要附加文件的临时文件。
注意:以上是一个未记录的内部 api,可能会发生变化 ( https://github.com/rails/rails/pull/37005 )
关于ruby-on-rails - 保存前从事件存储附件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57564796/