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.
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.
% 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
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
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
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