Conditionally targeting child element with turbo stream

I have a somewhat complicated question about turbo streams and broadcast_append_to

My markup is something like this

turbo_stream_from 'items'
<section id = container>
  <section id = category1>
  <section id = category2>

each Item would have a category of category1 or category2
In my model I have

after_create_commit { broadcast_append_to 'items', target: 'container' }

And this sort-of works, the item is appended to the container, but not inside the corresponding category element.

What I really want is for the items to be inside their corresponding category section, but I am not sure how to conditionally target my broadcast. Or am I just going about this all wrong?

So I found an answer, and I feel like a dope.

The answer was to get rid of the callback and put the broadcast into the controller’s create action. In there I was able to do something like

item.broadcast_append_to 'items' target: "#{item.category}"

And then it all started working fine…

1 Like