Pass record/row id on file upload in Editor

Pass record/row id on file upload in Editor

nhinzenhinze Posts: 6Questions: 1Answers: 0

I'm using Rails 8 and ActiveStorage to manage file attachments. Is there a way to pass the record/row id when uploading an attachment?

Using the code below, the editor properly replaces {id} with the row id when text inputs are changed. However, when uploading a file, the editor does not replace {id} with the row id. Therefore, I can't attach a file to my record in the backend.

The url generated is:

.../aircraft_flight_logs/{id}/upload

instead of

.../aircraft_flight_logs/123/upload

I understand you can't pass an id on a new record, but why not on an existing record while editing?

    const editor = new DataTable.Editor({
        ajax: {
            url: this.element.dataset.updateFlightLogUrl + '/aircraft_flight_logs/{id}',
            method: 'PATCH',
            headers: {
                'X-CSRF-Token': document.querySelector('[name="csrf-token"]').content
            },
            upload: {
                url: this.element.dataset.updateFlightLogUrl + '/aircraft_flight_logs/{id}/upload',
                type: 'POST',
                headers: {
                    'X-CSRF-Token': document.querySelector('[name="csrf-token"]').content
                }
            }
        },
        fields: this.getEditorFields(),
        table: '#aircraft-flight-log'
    });

Replies

  • allanallan Posts: 64,507Questions: 1Answers: 10,660 Site admin

    Is there a way to pass the record/row id when uploading an attachment?

    Generally no, as the row might not yet exist! Consider for example the "Create" view - the row doesn't exist in the database until the form has been submitted, and since the file is uploaded immediately upon selection (i.e. prior to the main form being submitted, there is no id!

    You could possibly limit it to edit only, but I think your best option might be to do a simple left join to a "files" table - the upload would return an id for the files table and then that id gets inserted as the value into the main table. You can see that approach in action here.

    Allan

Sign In or Register to comment.