如何向rails / actioncable中除发件人之外的所有客户端发送消息?
在socket.io中,您可以向除发件人之外的所有客户端发送消息,例如:
socket.broadcast.emit('user connected');
但在rails / actioncable中,怎么做?
class BoardChannel < ApplicationCable::Channel def subscribed stream_from "board:#{params[:board]}" end def speak # client will call @perform('speak') result = do_something() # how to send 'result' to all client except sender? end end
使用作业,您可以使用部分逻辑来实现。
在创建记录后的模型中,调用作业执行传递自记录。 请参阅下面如何使用广播将消息传递到收到的数据(在频道)。
... def perform(message) ActionCable.server.broadcast "board:#{params[:board]}", message: render_message(message) end private def ApplicationController.renderer.render( partial: 'messages/message.html.erb', locals: { message: message } ) end
在views / messages / _message.html.erb和代码make中创建一个部分
<%= if message.sender_id == current_user.id %> The code to report that forwarded message. <%= else %> The code to send the message to all except sender. <% end %>