Rails 7 turbo-stream broadcast to specific channel not working

1.3k Views Asked by At

I have a Post model and Comment, and Post has_many Comment and I wanna real-timely update the comment when you are in a specific post, meaning, the comments live-updating should only visible when multiple users are in the same post, for example: in posts/6

For View I have:

<div>
    <p>
      <strong>Title:</strong>
      <%= post.title %>
    </p>

    <p>
      <strong>Content:</strong>
      <%= post.content %>
    </p>

    <p>
      <strong>User:</strong>
      <%= post.user.username %>
    </p>
  </div>

  <hr/>

  <%= form_for [post, Comment.new] do |f| %>
    Body: <%= f.text_area :body, rows: 5, cols: 20 %>
    <%= f.submit "Submit" %>
  <% end %>

  <hr/>
  <h1>Comments:</h1>
  <%= turbo_stream_from post %>
  <%= turbo_frame_tag post do %>
    <div id="<%= dom_id(post) %>">
      <% post.comments.includes(:user).each do |comment| %>
        <%= render comment %>
      <% end %>
    </div>
  <% end %>

In Comment#create action I have:

    post = Post.find(params[:post_id])
    @comment = post.comments.new(comment_params)
    @comment.user_id = current_user.id

    respond_to do |format|
      if @comment.save
        
        format.turbo_stream { render turbo_stream: turbo_stream.prepend("post_#{post.id}", partial: "comments/comment", locals: { comment: @comment }) }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end

In Comment model I have:

after_create_commit { 
    broadcast_prepend_to(target: "post_#{self.post.id}")
    
  }

And in terminal I can see

[ActionCable] Broadcasting to : "<turbo-stream action=\"prepend\" target=\"post_6\"><template>  <div>\n    <p>\n      <strong>Title:</strong>\n      adsd\n    </p>\n\n    <p>\n      <strong>Content:</strong>\n      Asda\n    </p>\n\n    <p>\n      <strong>User:</strong>\n      Super Saiyan Vegeta\n    </p>\n  </div>\n\n  <hr/>\...

Which is correct, but the comments list in a specific post still not updating, and I do see I have id="post_6" in the view...can someone tell me why? Thanks.

1

There are 1 best solutions below

2
On

Try to change

<div id="<%= dom_id(post) %>">

to

<div id="post_<%= post.id %>">

And use such method in controller

if @comment.save
  @comment.broadcast_prepend_to to post, target: "post_#{post.id}", partial: "comments/comment", locals: { comment: @comment }
end

instead of broadcast from model