Почему ActionCable рендерит партиалы более одного раза? - PullRequest
0 голосов
/ 04 февраля 2019

Я создал систему уведомлений в стиле вещания с помощью actioncable.Это просто делает баннер, после того, как сообщение создано пользователем.После каждого обновления снова отображается баннер.

Я попытался установить ограничение create_at, которое загружает только записи, созданные 5 секунд назад, и я ограничил количество записей до 1 для самого последнего обновления.Даже в этом случае ограничение игнорируется, и частичное представление все равно отображается.

notify_followers_controller

class NotifyFollowersController < ApplicationController

  def index
    following_ids = current_user.following_users.pluck(:id)
    @notify_followers = NotifyFollower.where("created_at < ?", 5.seconds.ago).(user_id: following_ids).limit(1)
  end
end

channel / post_follower_notifier.coffee

App.post = App.cable.subscriptions.create PostChannel",
  connected: ->

  disconnected: ->

  received: (notify_follower) ->
# Called when there's an incoming data on the websocket for this channel
    $(".post-notification-location").prepend "<div class='notify_follower'> #{notify_follower.message}</div>"
    window.setTimeout (->
      $('.alert').fadeTo(500, 0).slideUp 500, ->
        $(this).remove()
        return
      return
    ), 5000

cable.js

// Action Cable provides the framework to deal with WebSockets in Rails.
// You can generate new channels where WebSocket features live using the `rails generate channel` command.
//
//= require action_cable
//= require_self
//= require_tree ./channels

(function () {

    this.App || (this.App = {});

    App.cable = ActionCable.createConsumer();

}).call(this);

application.js

//= require jquery3
//= require rails-ujs
//= require jquery-ui
//= require_tree .

post_channel.rb

class PostChannel < ApplicationCable::Channel
  def subscribed
    stream_from "post_channel"
  end

  def unsubscribed
    stop_all_streams
  end
end

connection.rb

module
  ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
    end

    protected

    def find_verified_user
      verified_user = User.find_by(id: cookies.signed['user.id'])
      if verified_user && cookies.signed['user.expires_at'] > Time.now
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end

Ожидаемые результаты: широковещательное сообщение должно отображаться только один раз после каждого сообщения.Фактические результаты: широковещательное сообщение отображается после каждого обновления.

...