Insert new record form using Turbo/Stimulus

Am I correct in that Turbo does not handle GET requests? I have a new.js.erb file that use UJS to insert a form into the DOM when a user clicks the ‘new record’ link. I thought I’d be able to simply change that to new.turbo_stream.eb and update that files contents to include a turbo-stream tag and template tag. But, this approach doesn’t work…because Turbo doesn’t process GET requests.

My question is: What is the future Rails way of handling inserting an inline form without UJS? I guess I could insert the form content using Stimulus and then insert the new record into the DOM using a stream. That seems like more work and more code than the UJS equivalent…but, the future seems to be moving away from UJS. Am I missing a concise and easier way to handle this task without UJS?

I suggest you watch the demo video on https://hotwired.dev/ which demonstrates what you are trying to accomplish.

Thanks! I will revisit that video.

Hi,

You could do a fetch post request in a stimulus controller with the correct header notamment “Accept”: “text/vnd.turbo-stream.html” and, then, in the controller do your stuff and don’t forget to have a view with the same name of your controller’s action like my_action.turbo_stream.html.

I use this kind of function like a js helper:

function fetchPostParams(data) {
  const params = {
    method: 'POST',
    headers: {
      "Content-Type": "application/json",
      "Accept": "text/vnd.turbo-stream.html",
      'X-CSRF-Token': document.head.querySelector("[name='csrf-token']").content
    },
    credentials: 'same-origin',
    body: JSON.stringify(data)
  }

  return params;
}

In a stimulus (or whatever) js controller, I do this:

fetch(myPostUrl, fetchPostParams(fetchData))
  .then(response => response.text())
  .then(html => Turbo.renderStreamMessage(html))

Cordialement,