I’m having a hard time wrapping my head around how to broadcast via a model and where the Hotwire magic stops and where I have to step in. Apologies if this has been covered, but I can’t seem to find what must be a common use case. Throughout my app, I want to scope updates to a specific user – or in this case, to a specific client.
My case:
I have a Client model. A Client has_many :hospitalizations.
I have two index views for hospitalizations.
One lists all hospitalizations:
views/hospitalizations/index.html.erb
views/hospitalizations/_hospitalization.html.erb
One is nested under clients:
views/clients/hospitalizations/index.html.erb
views/clients/hospitalizations/_hospitalizations.html.erb
views/clients/hospitalizations/_hospitalization.html.erb
I’d like to be able to update both the unscoped hospitalizations/index and the clients/hospitalizations/index.
So models/hospitalization.rb:
class Hospitalization < ApplicationRecord
belongs_to :client
belongs_to :staff
after_create_commit do
broadcast_prepend_to "hospitalizations",
partial: 'hospitalizations/hospitalization',
locals: { hospitalization: self },
target: 'hospitalizations'
broadcast_prepend_to :client,
partial: 'clients/hospitalizations/hospitalization',
locals: { hospitalization: self },
target: 'client_hospitalizations'
...
I wasn’t sure whether I’m supposed to do something with client.rb, so:
class Client < ApplicationRecord
broadcasts
...
And then, views/clients/hospitalizations/index.html.erb:
<%= turbo_stream_from :client %>
<%= render 'hospitalizations' %>
With the code I have now, when I create a new Hospitalization:
- hospitalizations/hospitalization works great. The new row is prepended.
- If I create a new hospitalization for client 4689, Hotwire will prepend the turbo-frame for all clients, not just 4689.
How do I scope the broadcast so that it only updates the client to whom the hospitalization belongs?