我在我的 Ruby on Rails 应用程序中使用 ActionCable 实现了一个实时通知系统,以启用服务器和客户端之间的 WebSocket 通信。但是,当创建新通知时,它并没有像预期的那样实时推送到客户端。我怀疑我的代码中可能存在极端级别的错误,但我似乎无法查明它。
我遵循了 Ruby on Rails 中 ActionCable 的标准实现:
创建了一个通知模型来表示每个通知。 设置一个 NotificationChannel 来处理 ActionCable 订阅。
# app/models/notification.rb
class Notification < ApplicationRecord
after_create_commit { broadcast }
private
def broadcast
ActionCable.server.broadcast("notifications:#{user_id}", {
notification: self
})
end
end
# app/channels/notification_channel.rb
class NotificationChannel < ApplicationCable::Channel
def subscribed
stream_from "notifications:#{current_user.id}"
end
def unsubscribed
# Any cleanup needed when the channel is unsubscribed
end
end
在我的通知模型中使用 after_create_commit 回调向客户端广播通知。 我希望当一个新的通知被创建时,它会被广播到客户端,JavaScript 代码会实时接收并在页面上呈现通知。
// app/javascript/channels/notification_channel.js
import consumer from "./consumer"
consumer.subscriptions.create("NotificationChannel", {
connected() {
console.log("Connected to the notification channel")
},
disconnected() {
console.log("Disconnected from the notification channel")
},
received(data) {
console.log("Received notification:", data)
// Render the notification on the page
}
})
实际发生的事情:
尽管正确设置了所有内容,但据我所知,通知并未实时推送到客户端。 JavaScript 代码似乎没有收到预期的通知,并且控制台中没有显示任何错误。