Hi everyone,
I hope 2022 is off to a good start for you.
I have an issue similar to this one but for some reason, the solution does not seem to work in my case.
Basically, I am trying to get familiar with Hotwire and I want to create a blog that works like a single-page app (so turbo stream the crud to change the content of the turbo_frame_tag
without reloading the page) but I also want to try out broadcasting both the posts
and the comments
in real-time.
The only thing not working is the broadcasting of the comments
, broadcasting the posts
work. I think it has to do with how I use the turbo_stream_from
, turbo_frame_tag
and/or the way I broadcast but I can’t seem to get it right.
My current posts/index
<%= turbo_stream_from "posts" %>
<div class="w-full">
[...]
<div class="min-w-full">
<%= turbo_frame_tag :posts do %>
<%= render @posts %>
<% end %>
</div>
</div>
he partial for each post is as follows:
<%= turbo_frame_tag post do %>
<div class="bg-white w-full p-4 rounded-md mt-2">
<h1 class="my-5 text-lg font-bold text-gray-700 text-4xl hover:text-blue-400">
<%= link_to post.title, post_path(post) %>
</h1>
[...]
</div>
<% end %>
the posts/show
replaces the current partial of each post with a more detailed version:
<%= turbo_stream_from @post, :comments %>
<%= turbo_frame_tag dom_id(@post) do %>
[...]
<div class="w-full bg-white rounded-md p-4 justify-start mt-1">
<div class="w-full pt-2">
<turbo-frame id="total_comments" class="mt-2 text-lg text-2xl mt-2 tex-gray-50">
<%= @post.comments.size %> comments
</turbo-frame>
<%= turbo_frame_tag "#{dom_id(@post)}_comments" do %>
<%= render @post.comments %>
<% end %>
[...]
</div>
</div>
</div>
<% end %>
with the respective models being:
class Post < ApplicationRecord
validates_presence_of :title
has_rich_text :content
has_many :comments, dependent: :destroy
after_create_commit { broadcast_prepend_to "posts" }
after_update_commit { broadcast_replace_to "posts" }
after_destroy_commit { broadcast_remove_to "posts" }
end
and
class Comment < ApplicationRecord
include ActionView::RecordIdentifier
belongs_to :post
has_rich_text :content
after_create_commit do
broadcast_append_to [post, :comments], target: "#{dom_id(post)}_comments", partial: 'comments/comment'
end
after_destroy_commit do
broadcast_remove_to self
end
end
The _comment
partial is
<%= turbo_frame_tag dom_id comment do %>
<div class="container w-full mx-auto bg-white p-4 rounded-md mt-2 border-b shadow">
<%= comment.content %> - <%= time_tag comment.created_at, "data-local": "time-ago" %>
[...]
</div>
<% end %>
Any idea what I am doing wrong?
Thanks a lot in advance and have a great day.