What are the best practices of updating multiple divs with ActionCable in Ruby on Rails?

Viewed 290

I have a Ruby on Rails site. One of the index pages has a table with multiple rows. I also have a background job that does certain operations on each row, which takes about 5-10 seconds each.

I would like to update the status for each row from 'Processing...' to 'Done' when the processing in the background job has completed.

I was thinking to use Action Cable to do the update, but to date I only used Action Cable to update only one element on a page, never multiple elements.

I was wondering what the correct way is to set-up my code to update the status in each row. Do I have to open a channel for each row separately?

1 Answers

Definitely You can do so. And you don't have to open channel for each row. Just use the job id whose status has been changed and id corresponding row in table with same id.

ActionCable.server.broadcast "job_status_update", job_id: 'xxxxx', status: 'complete'

.html

<table>
  <% jobs.each do |job|%>
   <tr>
     <td id="<%= job_id %>">
     <%= job.status %>
     </td>
   </tr>
 <% end %>
</table>

.coffee

App.chatChannel = App.cable.subscriptions.create { channel: "JobChannel" },
   received: (data) ->
     $(data.job_id).innerText(data.status)
Related