问题
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
- try to use url_for() funtion
file = JSON.parse(url_for(hlx_file))
- 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