我的应用程序中有2个用户类型(工作人员和公司)。两种用户类型都是通过Devise创建的。我目前正在尝试使用ActionCable向特定公司发送通知。
我的主要问题是,当我发送通知时,每个登录的公司都会收到该通知。我知道应该以某种方式在流名称中包含公司ID,但到目前为止我还没有运气。
我已经包含了向以下所有公司发送通知的工作代码:
notifications_channel.rb
class NotificationsChannel < ApplicationCable::Channel
def subscribed
stream_from "notifications_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
end
end
收听广播
ActionCable.server.broadcast 'notifications_channel', { 'My data' }
编辑
我使用javascript记录通知的状态:
notifications.js
App.notifications = App.cable.subscriptions.create("NotificationsChannel", {
connected: function() {
console.log("connected");
};
disconnected: function() {
console.log("disconnected");
};
received: function(data) {
console.log("recieved");
};
});
答案 0 :(得分:3)
像这样从您的控制器广播消息:
# Broadcast your message
ActionCable.server.broadcast "notifications_channel:#{target_user.id}
现在使用以下代码更新app/channels/application_cable/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.name
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
并订阅这样的流:
def subscribed
stream_from "notifications_channel:#{current_user.id}"
end
注意:这只是一个示例,说明如何在Actioncable中定位特定用户。您可能需要根据以下内容修改代码 您的要求。
我还建议您观看GoRails的video。
答案 1 :(得分:1)
我设法找到了解决方案。在遵循Abhilashs的回答后,我大部分时间都走了,但我仍然无法通过公司身份验证。似乎Warden尚未完全配置,所以这篇文章使它起作用了:env['warden'] not working with Rails 5