保存前从活动存储附件中读取
Reading from Active Storage Attachment Before Save
我有用户上传 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
。
您使用 before_save :set_name
在实际保存之前调用文件 您可以使用 after_save
而不是
- 尝试使用url_for()功能
file = JSON.parse(url_for(hlx_file))
- 也不要忘记
include Rails.application.routes.url_helpers
在你的模特身上
Rails6 将文件上传到存储的时刻改为记录实际保存的时刻
这意味着 before_save 或验证无法以常规方式访问文件。
如果您需要访问新上传的文件,您可以获得这样的文件参考:
record.attachment_changes['<attributename>'].attachable
这将是待附加文件的临时文件。
注意:以上是未记录的内部 api 并且可能会更改 (https://github.com/rails/rails/pull/37005)
我有用户上传 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
。
您使用 before_save :set_name
在实际保存之前调用文件 您可以使用 after_save
而不是
- 尝试使用url_for()功能
file = JSON.parse(url_for(hlx_file))
- 也不要忘记
include Rails.application.routes.url_helpers
在你的模特身上
Rails6 将文件上传到存储的时刻改为记录实际保存的时刻
这意味着 before_save 或验证无法以常规方式访问文件。
如果您需要访问新上传的文件,您可以获得这样的文件参考:
record.attachment_changes['<attributename>'].attachable
这将是待附加文件的临时文件。
注意:以上是未记录的内部 api 并且可能会更改 (https://github.com/rails/rails/pull/37005)