A
A
Andrey Baibek2020-01-30 12:30:49
Ruby on Rails
Andrey Baibek, 2020-01-30 12:30:49

How to load chat on the page after the page is loaded?

There is a page, on the left side is the usual content, on the right side is a chat. I want the chat to load after the page is loaded. Let's say I want to render a page with posts:

class PostsController < ApplicationController
    def index 
        @posts = Post.all
        @messages = Message.all # приходится тянуть в контроллер подгрузку сообщений из чата
        @message = Message.new # и новое сообщение для создания формы
    end
end

Or when I render the post creation page, I again have to pull the chat messages into the controller, etc. to each controller, which is bad. And if the chat was loaded after loading, or loaded once when the user connected to Action Cable, and then only updated using it, it would be great.
I write in Ruby On Rails and use Turbolinks, Stimulus and Action Cable for chat. What can you think of?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikola Okonesh, 2020-02-01
@AndreyBuyback

Here's a fairly simple method, so for example the sketch used setTimeout() to load the comments:
show.html.erb

<div class="d-block" id="comments-show-columns">
            <div id="open_comments" class="mt-4">
              <div data-controller="comments">
                Загрузка комментариев...
                <%= link_to url_for(open: 'true'), class: 'hidden', remote: true, data: {target: "comments.opencomment"} do %>
                <% end %>
              </div>
            </div>
          </div>

show.js.erb
<% if params[:open] %>
  var opening = document.querySelector("#open_comments")
  var pagin = document.querySelector("#comments-show-paginator")

  pagin.classList.toggle("hidden")
  opening.innerHTML = ('<%=j render(partial: "comments/comment", collection: @comments, locals: {full: true}, continue_thread: 10) %>')
<% end %>

app/javascript/controllers/comments_controller.js
import { Controller } from "stimulus";

export default class extends Controller {
  static targets = ["opencomment"]

  connect() {
    setTimeout(() => this.opencommentTarget.click(), 500 )
  }

}

Also, use data-turbolinks-permanent so that the chat does not visually reload when the page is rendered, and also the open_comments id must contain a page id like open_comments_<%= post .id %>.
Maybe there are other ways that it would be interesting to see.

A
alfss, 2020-01-30
@alfss

Write chat in JS. Provide an API for it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question