在一篇文章之后,我正在尝试 Rails Hotwire,并希望创建一个像单页应用程序一样工作的简单博客(即,turbo_stream
用于在不重新加载整个页面的情况下处理帖子和评论)。我还想通过对所有连接的浏览器实时进行 crud 操作来同时使用 actioncable。
posts/show
到目前为止,当我显示特定帖子(即)时,除了帖子评论的实时部分外,它正在工作。
它可能与我使用的标识符turbo_frame_tags
和/或我的方式有关,broadcast
但我似乎找不到答案。我查看了这个问题以及类似的 GoRails 示例,但它仍然不起作用。
我现在的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>
每个帖子的部分内容如下:
<%= 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 %>
用更详细的posts/show
版本替换每个帖子的当前部分:
<%= 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 %>
各自的模型是:
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
和
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
_comment
部分是
<%= 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 %>
如前所述,帖子工作的实时 crud 工作而不是他们的评论。知道我做错了什么吗?提前致谢。