There's no limit (within reason) to how many subscriptions you can open on a single page, and as you'll soon learn, you can provide several keys which mix many different types, including ActiveRecord model resources, strings, integers, class constants and more.
We're going to use a ActiveRecord model callbacks to demonstrate updating likes on a Photo resource.
First, let's set up a
/photos index page and quickly sketch a basic
photo partial which will provide our user interface:
<h1>Photos!</h1> <%= cable_ready_stream_from Photo %> <div id="photos"> <%= render @photos %> </div>
cable_ready_stream_from view helper is an invisible web component that doesn't occupy any space in your layout. By passing it
Photo, we're telling it to listen for any CableReady broadcasts that specify
Photo as a key. This implies that you'll be sending updates targeting "all photos", as evidenced by the
div with the
photos id which will contain all of the photos.
This is perfect for adding new photos to an existing list. We should keep the
cable_ready_stream_from helper outside of the
div just in case you ever want to update its contents.
<div id="<%= dom_id(photo) %>"> <%= cable_ready_stream_from photo %> <img src="<%= photo.path %>" /> Likes: <%= photo.likes %> <%= form_with model: photo, local: false do |form| %> ... <% end %> </div>