Want to broadcast new objects scoped to logged in User

This is my first experience with Turbostream Broadcasts, so please forgive my rudimentary understanding…

I have an app where each User has many cars (cars belong_to user).

When a user creates a car, i’m trying to broadcast that new car to all Cars>Index pages that the Car’s User is logged into (I’m using Devise, but not including current_user in any partials).

But instead, when you create a car, the new car is broadcast to EVERY user’s Cars>Index page, so another user could suddenly see a car they didn’t create. Not good! :wink:

I’d like to scope the broadcast just to the user’s Cars Index page who created the car.

Any thoughts on how I might do that? Thanks very much!

Here is the code that allows me to broadcast new cars to ALL users’ Cars index pages…

  belongs_to :user
  after_create_commit { broadcast_prepend_later_to('cars', target: 'all_cars') }
  after_update_commit { broadcast_replace_later_to :cars }
  after_destroy_commit { broadcast_remove_to :cars }
    <div id="all_cars">
      <%= turbo_stream_from :cars %>
      <% @cars.each do |car| %>
        <%= render 'car', car: car%>
      <% end %>

Hi @k2director :slight_smile:

I don’t know if that answers specifically your question but there is here a beginning of the answer.
As mentioned in this SO thread, there is an active discussion on this forum you can find here as well as an article worth reading here.

In a nutshell, I guess the idea would be to scope who can view the updates based on the partial you broadcast and passing variables to handle that filtering (as described in the thread, for example, passing current_user as a variable).

(As an alternative also, I think StimulusReflex can be interesting since it can access more “backend” information with helpers like updates_for)

I hope this helps you a bit.

My understanding is that the correct approach is to scope the broadcast commands with the user (or in my case account)

so I use

broadcasts_to ->(faq) { [faq.account, :faqs] }, target: "faqs"
//note that broadcasts_to is essentially a shortcut for your three broadcast commands

and on the view side

= turbo_stream_from current_account,"faqs"

the stream name is generated from the account and the key (and then signed), It can’t be guessed, so the only way to listen to the stream is to be the correct account in the first place.

you would use

after_create_commit { broadcast_prepend_later_to([current_user,:cars], target: 'all_cars') }
<%= turbo_stream_from [current_user,:cars] %>

1 Like

Thanks much for the answers. I’m going to study these and dive in again as soon as I’m done with my current tasks. Much appreciated…

Just following up and wanted to thank you for this explanation/example. It worked perfectly. Much appreciated!

1 Like