Simplest way to achieve this? (Turbo Streams)

Dear community,

please excuse the amateur nature of my question. I’m totally new to Turbo, but also already intrigued by its possibilities and most importantly the low amount of code to write to achieve complex things.

I would like to start with a small goal, but for now I was unable to find a good tutorial or example to show me the basics without overloading the capacity of my brain.

Maybe you can help me with just a little hint on how one would achieve this the simplest way?

In a fresh Rails 7 app I have a list of people names that is shown like this:

my index.html.erb looks like this:

<div id="people">
	<table width=200>
			<% @people.each do |person| %>
				<td><%= %></td><td><%= link_to "Details", person %></td>
			<% end %>
	<p><%= link_to "New person", new_person_path %></p>

I would like this page to automatically update for all visitors, as soon as the list of names is changed via Rails console. Can you help me and give me a hint on which changes would be necessary to achieve this?

Thank you so much in advance for your patience to help!

Best regards

You probably would want to extract the row for each person into a partial then you can replace it whenever the record is updated
Add a dom_id to make a unique id for the record

 # people/_person.html.erb
<tr id="<%= dom_id(person) %>">
  <td><%= %></td><td><%= link_to "Details", person %></td>

You also need to make a turbo-stream-connection in the view

# index.html.erb
<%= turbo_stream_from :people %>
# models/person.rb
after_update_commit :broadcast_person

def broadcast_person
  # it will use the person partial by default

Because of the dom_id when the partial is broadcasted to people it will replace the old one

1 Like

Hey and thank you very much for your help!

I followed your recommendations and it helped me to get some first feelings of success :sweat_smile:

When changing names, the site now automatically updates!

Only when creating or destroying entries, it doesn’t keep up. I tried after_create_commit and after_destroy_commit for the model, but unfortunately without success. Do I have to do something different here?


You can either switch to using broadcasts_to to define after create, update, and destroy for you

# person.rb
broadcasts_to -> (person) { :people }

Or you can write different broadcast methods for each callback manually
All of the available actions are defined here in the code and there is inline documentation

after_destroy_commit { broadcast_remove_to(:people) }
after_create_commit { broadcast_append_to(:people) }

Thank you!

It seems like there is a lot left to study for me. For now, this is enough help to assist me on my way. Thanks for your help and patience!