gpt4 book ai didi

ruby-on-rails - Rails Action 电缆特定消费者

转载 作者:行者123 更新时间:2023-12-04 06:24:24 25 4
gpt4 key购买 nike

我正在努力解决 Action 线 .就我而言,我有几个用户(通过 Devise )可以彼此共享任务。

现在当user#1user#2 共享任务(通过表单)所有经过身份验证的用户都会收到通知。

我应该如何以及在哪里识别我的user#2只向他广播?

到目前为止,这是我的代码:

连接.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.id
end

protected

def find_verified_user # this checks whether a user is authenticated with devise
if verified_user = env['warden'].user
verified_user
else
reject_unauthorized_connection
end
end
end
end

电缆.js
(function() {
this.App || (this.App = {});

App.cable = ActionCable.createConsumer();

}).call(this);

todo_channel.rb
class TodoChannel < ApplicationCable::Channel
def subscribed
stream_from "todo_channel_#{current_user.id}"
end

def unsubscribed
# Any cleanup needed when channel is unsubscribed
end


def notify
ActionCable.server.broadcast "todo_channel_#{current_user.id}", message: 'some message'(not implemented yet)
end
end

todo.coffee
App.todo = App.cable.subscriptions.create "TodoChannel",
connected: ->
# Called when the subscription is ready for use on the server

disconnected: ->
# Called when the subscription has been terminated by the server

received: (data) ->
console.log(data['message'])

notify: ->
@perform 'notify'

最佳答案

我之前也遇到过类似的情况,直到我意识到您实际上可以调用 stream_from在 channel 中多次,该用户将在同一 channel 连接中订阅多个不同的“房间”。这意味着你基本上可以做到这一点

class TodoChannel < ApplicationCable::Channel
def subscribed
stream_from "todo_channel_all"
stream_from "todo_channel_#{current_user.id}"
end

def unsubscribed
# Any cleanup needed when channel is unsubscribed
end

def notify(data)
# depending on data given from the user, send it to only one specific user or everyone listening to the "todo_channel_all"
if data['message']['other_user_id']
ActionCable.server.broadcast "todo_channel_#{data['message']['other_user_id']}", message: 'some message'
else
ActionCable.server.broadcast "todo_channel_all", message: 'some message'
end

end
end

该代码假设用户已经知道其他用户的 id 并将其发送到 channel ,您可能必须用一些安全性或其他东西来包装它,我承认我对 rails 的经验不是很好,因为我还在学习。

将来可能对您有益的另一件事是,您还可以在同一 channel 功能中广播多个消息/时间。这意味着您可以潜在地支持将您的任务发送给单个特定用户、特定用户列表或每个人。只需在列表/数组/任何用户上进行迭代,然后在他们的个人“todo_channel_#{user.id}”上向他们广播任务/消息/通知/任何内容

关于ruby-on-rails - Rails Action 电缆特定消费者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39805852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com