Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from Active Storage Attachment Before Save

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.

like image 537
Frank Avatar asked Jan 01 '23 17:01

Frank


1 Answers

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)

like image 128
ahmeij Avatar answered Jan 05 '23 14:01

ahmeij