Rails 5 – 如何以实时方式发送通知?

在rails 5中,我试图以实时方式发送通知。 我已经提到了http://jameshuynh.com/rails/react%20js/chat/2017/07/30/build-chat-using-react-js-and-rails-action-cable/

但我已经有一些方法也会这样做。 根据此方法,通知应基于user_id动态发送。 甚至频道取决于user_id。

在react,header.jsx文件中,

 import ActionCable from 'actioncable'; export default class Header extends React.Component { cable = ActionCable.createConsumer('ws://localhost:3000/cable'); componentDidMount() { HttpService.get('/api/v1/notifications', this.getNotificationsSuccess); let that = this; this.cable.subscriptions.create("NotificationsChannel", { user_id: this.state.currentUser.id, connected: function () { // Timeout here is needed to make sure Subscription // is setup properly, before we do any actions. setTimeout(() => this.perform('follow', { user_id: this.user_id }), 1000); }, received: (response) => that.addNotification(response) }); } addNotification = (response) => { if(this.refs.notifications){ this.refs.notifications.addNotification(response.data.notification); } } 

在rails中,connection.rb,

 module ApplicationCable class Connection < ActionCable::Connection::Base identified_by :current_user def connect self.current_user = find_verified_user logger.add_tags 'ActionCable', current_user.full_name end protected def find_verified_user verified_user = User.find_by(id: cookies.signed['user.id']) if verified_user verified_user else reject_unauthorized_connection end end end end 

在notification_channel.rb中,

 class NotificationsChannel < ApplicationCable::Channel def follow(data) stop_all_streams stream_from "notifications:#{data['user_id'].to_i}" end def unfollow stop_all_streams end end 

在notification_broadcast_job.rb中,

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

在模型中,

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

使用此现有方法,如何检查实时通知是否有效? 现在没有错误,它也没有工作。 请帮我实现此function。