Rails 7.0.1 ActiveStorage::InvalidDirectUploadTokenError (ActiveStorage::InvalidDirectUploadTokenError):

Trying out activestorage (7.0.1), with the JS “@rails/activestorage”: “^7.0.1”,

Have a Shop model with a file attachment. Using the form_with(model: @shop, direct_upload: true) and a form.file_field helper, I am seeing most of the info needed for a successful Direct Upload, except the critical two fields:

direct-upload-token is not rendered and there is no direct-upload-attachment-name generated either, when I inspect the generated DOM element.

So when I go to upload, the server throws a 500 error on invalid upload token. I am at a loss as to why this. How can I get the file_field helper to provide those values in a Rails 7 project?

1 Like

Don’t bother trying to fix your code. This is because of a new feature whose implementation the core devs decide to redo because of how much trouble it is causing. For now, simply monkey patch your app to force rails back to the old behaviour. Basically, create this initializer:

Rails.application.config.after_initialize do
  ActiveStorage::DirectUploadsController.class_eval do
    private
      def verified_service_name
        ActiveStorage::Blob.service.name
      end
  end

  ActionView::Helpers::FormTagHelper.module_eval do
    private
      def convert_direct_upload_option_to_url(_, options)
        if options.delete(:direct_upload) && respond_to?(:rails_direct_uploads_url)
          options["data-direct-upload-url"] = rails_direct_uploads_url
        end
        options
      end
  end
end
1 Like

For reference, here’s the discussion about scrapping the current implementation:

It’s been reverted. If you are using Rails 7.0.2 you don’t have to worry about this.

1 Like