唯一改变的是你订阅的频道。在这种情况下,它应该是一个特定的对话。你可以这样做:
消息.咖啡
$(document).on "turbolinks:load", ->
messages = $("#messages-list")
App.Messages = App.cable.subscriptions.create {
channel: "MessagesChannel"
# You can grab the conversation id as a data attribute from the messages container of your conversation and pass it as a parameter to the channel
conversation_id: messages.data("conversation-id")
},
connected: ->
disconnected: ->
# Called when the subscription has been terminated by the server
received: (data) ->
messages.append(data["message"])
$("#new_message")[0].reset();
消息_频道.rb
class MessagesChannel < ApplicationCable::Channel
def subscribed
stream_from "conversation_#{params['conversation_id']}_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
消息_控制器.rb
# You can have something like this in your create action
def create
message = @conversation.messages.build(message_params)
message.user = current_user
message.save
ActionCable.server.broadcast "conversation_#{message.conversation.id}_channel",
message: render_message(message)
head :ok
end
private
def set_conversation
@conversation = Conversation.find(params[:conversation_id])
end
def render_message(message)
render partial: "messages/message", locals: { message: message }
end