Hotwire Confusion

Hi, I was watching this video yesterdy and at 5:50 he added a turbo_stream format.

What confused me is how does the app know it’s a turbo_stream format? I didn’t notice anything being added to the form to indicate that? How does it differentiate from a standard HTML format?

1 Like

If you try it out - you’ll see :sunglasses:

What you’ll (hopefully) see is that when submitting the message form, (in the terminal where your ‘rails server’ process is running) a line with something like

Started POST "/messages" for ::1 at 2022-11-25 13:09:28 +0100
Processing by MessagesController#create as TURBO_STREAM

(it might not necessarily be exactly like the above, but close enough I’d say -

The form is being post’ed by the hotwired javascript intercepting the <a> and <button type=“submit”> clicks and generates an AJAX request which in turn is being understood by the router/controller as TURBO and your create controller action will ‘fall’ into the turbo_stream format and render a new message form as an HTML fragment and puma will return the fragment as the response to your request, in effect pushing it down the wire to the hotwired javascript (a)waiting in your browser background, in anticipation of any news; and when it arrives it will replace the element (the entire form encapsulated in the ‘new_message’ id’ed div) with the html fragment received in the response - all pretty standard ajax stuff, just sugared-up hard :wink:

that’s my understanding at least
:nerd_face: :sweat_smile:

Thanks for that, I understand all the flow, just not the part where the form switches from a standard post request to an ajax request via Turbo?

I understand every other part but there’s that one gap that i’m obviously missing.

the - beauty if you will - of Hotwire is exactly that.

It starts out as standard get/post and all of a sudden it “transmogifs” into something else (turbo)

it’s at your discretion to deactivate the turbo part simply by adding an attribute to the submit button telling it to not submit as turbo - and then it will post as standard

<form action="/messages" method="post" data-turbo="false">

Try that - and see the difference in your terminal

Thought it might be worth noting some of the finer details/mechanics. If you inspect the Network requests while submitting a Turbo-enabled form, you’ll see in the HTTP Headers that the Accept is set to text/vnd.turbo-stream.html. You’ll also see this same value on the HTTP Headers of the response as the Content-Type.

Directly from the handbook,

When submitting a <form> element whose method attribute is set to POST , PUT , PATCH , or DELETE , Turbo injects text/vnd.turbo-stream.html

That Accept HTTP Header on the request is what Rails uses to determine that the request has been via TURBO_STREAM.