About immediate comment update function

Action Cable To implement the instant message update feature, we use a framework called ** Action Cable **. This framework is similar to a regular Rails application and can implement immediate updates.

Channel

In order to display comments etc. immediately, we write JavaScript that sets the data route and displays the sent data, but it is ** Channel * that plays these roles. *is. It is a server-side mechanism that realizes the immediate update function.

Implementation method

① Create channel

% rails g channel comment

Executing this command in the terminal will create the following files.

Running via Spring preloader in process 11084
      invoke  test_unit
      create  test/channels/comment_channel_test.rb
      create  app/channels/comment_channel.rb
   identical  app/javascript/channels/index.js
   identical  app/javascript/channels/consumer.js
      create  app/javascript/channels/comment_channel.js

② Edit comment_channel.rb

This file connects the server and the client, and uses the ** stream_from ** method to set the server-client association.

class MessageChannel < ApplicationCable::Channel
  def subscribed
    stream_from "comment_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end

③ Edit comments_contorller.rb

Describe so that the comment will be sent via ** broadcast ** when the comment is saved successfully.

class CommentsController < ApplicationController
  def new
    @comments = Comment.all
    @comment = Comment.new
  end

  def create
    @comment = Comment.new(text: params[:comment][:text])
    if @comment.save
      ActionCable.server.broadcast '@comment_channel', content: @comment
    end
  end
end

④ Edit 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.text}</p>`;
    const comments = document.getElementById('comments');
    const newComment = document.getElementById('comment_text');
    comments.insertAdjacentHTML('afterbegin', html);
    newComment.value='';
  }
});

Recommended Posts

About immediate comment update function
About error handling of comment function
Implemented comment function
About the function double-java
App creation comment function asynchronous
About adding a like function
[Rails] About flea market app product editing function (preview editing / DB update)
Real-time comment function with Action Cable (2/2)
[Rails] About the Punk List function
[Rails] About implementation of like function
[Rails] Comment function (registration / display / deletion)
Real-time comment function with Action Cable (1/2)
[Ruby on Rails] Comment function implementation
[Rails] Comment function implementation procedure memo