how to send message to all client except sender in rails/actioncable?

那年仲夏 提交于 2019-12-04 10:43:17

问题


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

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

but in rails/actioncable, how to do that?

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:


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

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


来源:https://stackoverflow.com/questions/38892367/how-to-send-message-to-all-client-except-sender-in-rails-actioncable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!