前提・実現したいこと
現在、ActionCableを用いたコメント機能の実装を行っているのですが、
コメントを入力後画面が一度リロードされてからコメントの表示がされており、即時更新ができず困っています。
原因がお分かりになる方、いらっしゃいましたらご教授お願い致します。
発生している問題・エラーメッセージ
デスクトップ上にエラーメッセージは表示されていませんが rails sでサーバーを起動させた際、ターミナルに
CommentChannel is transmitting the subscription confirmation
CommentChannel is streaming from comment_channel
と出力されています。
挙動的には、コメントの投稿後に即時更新でコメントの表示を行いたいところ
現在、コメント⇨画面が自動リロードされてからコメントが表示されている状態です。
該当のソースコード
comments_controller
ruby
1class CommentsController < ApplicationController 2 3 def create 4 @comment = Comment.create(comment_params) 5 #redirect_to "/recipes/#{@comment.recipe_id}" 6 if @comment.save 7 ActionCable.server.broadcast 'comment_channel', content: @comment 8 end 9 end 10 11 private 12 def comment_params 13 params.require(:comment).permit(:comment).merge(user_id: current_user.id, recipe_id: params[:recipe_id]) 14 end 15end
channels/comment_channel.rb
class CommentChannel < ApplicationCable::Channel def subscribed stream_from "comment_channel" end def unsubscribed # Any cleanup needed when channel is unsubscribed end end
javascript/channels/comment_channel.js
import consumer from "./consumer" consumer.subscriptions.create("CommentChannel", { connected() { // Called when the subscription is ready for use on the server }, disconnected() { // Called when the subscription has been terminated by the server }, received(data) { const html = `<p>${data.content.comment}</p>`; const comments = document.getElementById('comments'); const newComment = document.getElementById('recipe_comment_comment'); comments.insertAdjacentHTML('afterbegin', html); newComment.value = ''; } });
show.html.erb
~~~省略~~~ <%# コメント投稿機能 %> <div class="comment__container"> <% if user_signed_in? %> <%= form_with(model: [@recipe, @comment], local: true) do |f| %> <%= f.text_area :comment, placeholder: "コメントする", rows: "2" %> <%= f.submit '送信' %> <% end %> <% else %> <strong><p>※※※ コメントの投稿には新規登録/ログインが必要です ※※※</p></strong> <% end %> <div class="comments"> <h4><コメント一覧></h4> <% @comments.each do |comment| %> <strong><%= link_to comment.user.nickname, "/users/#{comment.user_id}" %>:</strong> <p><%= comment.comment %></p> <% end %> </div> </div>
試したこと
javascript/channels/comment_channel.js の newComment の定義部分が comment_comment となっていたため、recipe_comment_comment へ記述変更しましたが、即時更新機能の実現には至りませんでした。
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/10/19 08:20