为什么ActionCable渲染子对象不止一次?

时间:2019-02-03 22:30:43

标签: javascript ruby-on-rails ruby websocket actioncable

我创建了一个带有actioncable的广播样式通知系统。在用户创建帖子后,这只是呈现横幅。每次刷新后,横幅会再次显示。

我尝试设置了created_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

channels / 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

预期结果:广播消息在每个帖子之后仅应呈现一次。实际结果:广播消息在每次刷新后呈现。

0 个答案:

没有答案