Frank
Frank

Reputation: 949

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.

Upvotes: 8

Views: 5746

Answers (2)

knutsel
knutsel

Reputation: 1291

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)

Upvotes: 16

Hisham Magdy
Hisham Magdy

Reputation: 144

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

Upvotes: 0

Related Questions