LoginSignup
mako1111
@mako1111 (mako chan)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

ActionCableでコメント削除ボタンを条件分岐

解決したいこと

現在、ActionCableを用いてリアルタイムコメント投稿機能を実装中。
LINEのグループチャットのようなコメント機能でコメント投稿時に削除ボタンも同時に送信しているのだが、条件分岐が適応されなく悩んでいます。

現状の実装

❶コメントcreate時にデータとしてchannelにコメント情報を送信
❷chanellでinsertHTMLでコメントと削除ボタンを挿入
❸期待する結果は、条件分岐をログインユーザーとコメント投稿ユーザーの一致によって行い、削除ボタンの有無を判断する

該当するソースコード

#commnents_controller.rb
class CommentsController < ApplicationController
  def create
    @post = Post.find(params[:post_id])
    # 投稿に紐づいたコメントを作成
    @comment = @post.comments.build(comment_params)
    @comment.user_id = current_user.id
    if @comment.save
      ActionCable.server.broadcast 'message_channel', content: @comment, user: @comment.user,
                                                      date: @comment.created_at.to_s(:datetime_jp), id: @comment.id, post: @comment.post,
                                                      current_user: current_user
    end
  end
#message_channel.js
import consumer from "./consumer"
window.addEventListener('load', function(){

consumer.subscriptions.create("MessageChannel", {
  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) {

    if (data.user.id === data.current_user.id){
      var de = `<a id="delete-btn", data-method="delete" href="/posts/${data.post.id}/comments/${data.id}"><button id="${data.id}">削除</button></a>` ;
      console.log(document.getElementById('row').dataset.id = data.current_user.id)
      console.log(data.current_user.id)
    }else{
      var de = "" ;
      console.log("empty")
    };

    const html = `<div id="data-test-${data.id}">
                  <p><a href="/users/${data.user.id}">@${data.user.nickname}</a></p>
                  <span style="font-weight:bold;">${data.content.content}</span>
                  &nbsp;${data.date}
                  ${de}
                  </div>`;

    const messages = document.getElementById('row');
    const newMessage = document.getElementById('comment_content');
    messages.insertAdjacentHTML('beforeend', html);
    newMessage.value='';
  }
});
})

備考

  • data.user.id→取得できている
  • data.current_user.id→取得できている
    比較に一致しない場合も本番環境で削除ボタンが表示されててしまう→比較ができていない?

良いアクションプランございましたら、教えていただけると幸いです。。

0

No Answers yet.

Your answer might help someone💌