Reading from Active Storage Attachment Before Save

廉价感情. 提交于 2019-12-24 20:05:15

问题


I have users uploading JSON files as part of a model called Preset, very standard Active Storage stuff. One thing that's somewhat out of the ordinary (I suppose, given my inability to make it work) is that I'd like to grab data from the uploaded JSON file and use it to annotate the Preset record, like so:

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

When I call hlx_file.download I get ActiveStorage::FileNotFoundError: ActiveStorage::FileNotFoundError.


回答1:


Rails 6 changed the moment of uploading the file to storage to during the actual save of the record.

This means that a before_save or validation cannot access the file the regular way.

If you need to access the newly uploaded file you can get a file reference like this:

record.attachment_changes['<attributename>'].attachable

This will be a tempfile of the to-be-attached file.

NOTE: The above is an undocumented internal api and subject to change (https://github.com/rails/rails/pull/37005)




回答2:


you use before_save :set_name which call the file before it actually being saved you can use after_save instead

  1. try to use url_for() funtion file = JSON.parse(url_for(hlx_file))
  2. also dont forget to include Rails.application.routes.url_helpers at your model


来源:https://stackoverflow.com/questions/57564796/reading-from-active-storage-attachment-before-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!