如何向rails / actioncable中除发件人之外的所有客户端发送消息?

时间:2021-07-03 18:08:38

in socket.io, you can send message to all client except sender like:

在socket.io中,您可以向除发件人之外的所有客户端发送消息,例如:

socket.broadcast.emit('user connected');

but in rails/actioncable, how to do that?

但在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

1 个解决方案

#1


0  

Using jobs, you can make this with the logic in a partial.
In your model after create a record, call the job perform passing the self record. See bellow how pass message to recieved data(at channel) using broadcast.

使用作业,您可以使用部分逻辑来实现。在创建记录后的模型中,调用作业执行传递自记录。请参阅下面如何使用广播将消息传递到收到的数据(在频道)。

   ...  

   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  

Create a partial in views/messages/_message.html.erb and in your code make

在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 %>

#1


0  

Using jobs, you can make this with the logic in a partial.
In your model after create a record, call the job perform passing the self record. See bellow how pass message to recieved data(at channel) using broadcast.

使用作业,您可以使用部分逻辑来实现。在创建记录后的模型中,调用作业执行传递自记录。请参阅下面如何使用广播将消息传递到收到的数据(在频道)。

   ...  

   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  

Create a partial in views/messages/_message.html.erb and in your code make

在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 %>