I want to broadcast updates of ActiveRecord to distinct partials depending on their scoped route. How could I do that?
Ex: I have a Post model that has_many :comments
. Comments can be updated and we have two partials for a comment
in the following folders to display them using a distinct template:
<%= turbo_stream_from comment %>
<%= turbo_frame_tag dom_id(comment) do %>
//one way of displaying the comment
<% end %>
<%= turbo_stream_from comment %>
<%= turbo_frame_tag dom_id(comment) do %>
//another way of displaying the comment
<% end %>
Every time I update the record it is broadcasted using turbo-stream.
class Comment < ApplicationRecord
broadcasts_to :post
end
The issue is that the broadcasted result is using the /views/comments/_comment.html.erb
all over the application.
I would want a way to broadcast and re-render the comment using the scoped partial when the view is under a specific scope, and to use the unscoped partial when no scope is defined, is that even possible?
I found the answer in the gem...
This can be performed by changing the dom_id of the visitor comment to "#{dom_id(comment)}_visitor"
and passing the partial explicitly in the broadcast_replace_to
<%= turbo_stream_from comment %>
<%= turbo_frame_tag "#{dom_id(comment)}_visitor" do %>
//another way of displaying the comment
<% end %>
class Comment < ApplicationRecord
after_update_commit do
broadcast_replace_to self
broadcast_replace_to self, target: "#{dom_id(self)}_visitor", partial: 'visitor/comments/comment'
end
end