【问题标题】:Rails 5 - How to revert/delete the already broadcasted notification?Rails 5 - 如何恢复/删除已经广播的通知?
【发布时间】:2018-03-22 06:25:12
【问题描述】:

在 Rails 5 中,我使用ActionCable 实时广播通知。一旦创建Notification 对象,就会发生广播。现在我想在Notification 对象被删除时恢复广播通知。

在notification_broadcast_job.rb中,

def perform(notification, user_id)
  ActionCable.server.broadcast "notifications:#{user_id}", data: NotificationSerializer.new(notification)
end

在notification.rb中,

after_commit :broadcast_notification

private

def broadcast_notification
  users.each do |user|
    NotificationsBroadcastJob.perform_later(self, user.id)
  end
end

现在的问题是,当用户 A 喜欢属于用户 B 的一篇帖子时,B 将收到通知(无需重新加载页面)。当用户 A 立即不喜欢它时,应该从用户 B 发出通知(无需重新加载页面)。现在删除的对象(通知)将简单地显示在一个列表中。

我该如何解决这个问题?请帮帮我。

【问题讨论】:

    标签: ruby-on-rails ruby notifications broadcast actioncable


    【解决方案1】:

    您的问题是您无法区分对象Notification 是创建还是删除?

    您可以使用after_createafter_destroy 代替after_commit

    后端将数据传递给前端,然后前端将显示或隐藏数据。关键是font-end需要知道是显示还是隐藏。因此,前后之间应该有一个协议。没有优雅的例子:

    在notification.rb中,

    after_create :broadcast_notification
    after_destroy :delete_notification
    private
    
    def broadcast_notification
      users.each do |user|
        NotificationsBroadcastJob.perform_later(self,'created', user.id)
      end
    end
    
    def delete_notification
      users.each do |user|
        NotificationsBroadcastJob.perform_later(self,'delete', user.id)
      end
    end
    

    在notification_broadcast_job.rb中,

    def perform(notification, message_type , user_id)
      ActionCable.server.broadcast "notifications:#{user_id}", data:{ message_type: message_type, info: {id: notification.id, body: notification.body}}
    end
    

    前端会先读取message_type。然后它知道显示或隐藏某些东西。

    前端js代码:

    if(data.message_type == 'created'){
      $('***').append('<li id=' + data.info.id + '>' + data.info.body +'</li>'); // 
    }else{
      $('#'+ data.info.id).hide();
    }
    

    【讨论】:

    • after_destroy方法中应该怎么做?
    • 你能再详细点吗?
    • after_commit下已经有一个广播相关的方法写了。我应该如何在after_destroy 中编写其还原(广播)代码?
    猜你喜欢
    • 2021-02-12
    • 2023-03-12
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    相关资源
    最近更新 更多