Hotwire Discussion

Turbo Streams - Web Sockets vs Controller Responses in Rails

Sorry if I’ve completely misunderstood how this works.

At the moment, I’ve got a Rails app that, for the most part is built using lots of Turbo Frames and it works really well - inline editing, form submissions and redirects all doing what I expect, and I’ve got the responsiveness of an SPA while writing traditional Rails code.

The next step is to have stuff auto-updating - if I’ve got a view open with a load of models displayed and someone else edits one of those models, my view automatically updates.

So I use turbo_stream_from @something and make sure my IDs and partials are set up correctly. Then I add broadcasts_to :something to my model - and everything works nicely.

But this is a big application, and there are several places where the same model can be viewed - each in slightly different formats.

I can add multiple broadcasts statements into my model - but they all reference the same partial. I could pass in the HTML - but I’m embedding HTML into my model and it might not match the already-rendered view as I edit stuff. Or I could render the partial within my model, which feels horrible and is quite unwieldy - I guess the solution I’m looking for is to be able to specify which partial to use in the call to broadcasts?

Alternatively, I could return turbo-streams from my controllers. Then I can use a turbostream.erb file and have multiple responses going out at the same time. But I assume that these controller responses will only go back to the caller - and won’t get broadcast to all subscribers of the websocket? Is that correct?

Got it!

I can’t use broadcasts_to but if I use an after_commit then I can specify the partial in my call to broadcasts_update_later_to within my callback.