我有一个基本的设置,rails + devise + actioncable。
我基本上想直接和私下发送通知给目前已登录的用户。我的代码如下所示:
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.email
end
private
def find_verified_user
if verified_user = env['warden'].user
verified_user
else
reject_unauthorized_connection
end
end
end
endnotifications_channel.rb
class NotificationsChannel < ApplicationCable::Channel
def subscribed
stream_from current_user
end
end一切都很顺利。客户端已连接,我可以在日志中看到他正确地登录。此外,我还可以在rails控制台中看到以下输入:
[ActionCable] [admin@example.com] Registered connection (Z2lkOi8vcHJpc21vL1VzZXIvMQ)
[ActionCable] [admin@example.com] NotificationsChannel is transmitting the subscription confirmation
[ActionCable] [admin@example.com] NotificationsChannel is streaming from #<User:0x00007f87f4180b68>但是,当试图使用下面的代码向该用户发送通知时,事件似乎没有到达用户(没有出现错误!):
2.5.1 :010 > NotificationsChannel.broadcast_to(User.first, test: 'foo')
[ActionCable] Broadcasting to notifications:Z2lkOi8vcHJpc21vL1VzZXIvMQ: {:test=>"pass"}
=> nil我的javascript使用者没有记录任何东西:
let cable = ActionCable.createConsumer(`ws://mydomain.com/cable`)
let actions = {
received(payload) {
console.log(payload) // <== this line logs nothing!
}
}
cable.subscriptions.create('NotificationsChannel', actions)我在这里做错什么了吗?
发布于 2018-10-09 18:02:40
这可能是因为您使用的是stream_from而不是stream_for。当在通道中引用对象(模型)而不是字符串时,应该使用stream_for。尝试在notifications_channel.rb中这样做
class NotificationsChannel < ApplicationCable::Channel
def subscribed
stream_for current_user
end
end以下是对文档的引用:for
https://stackoverflow.com/questions/52726725
复制相似问题