首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >rails 5-通过ActionCable创建每个会话的通道

rails 5-通过ActionCable创建每个会话的通道
EN

Stack Overflow用户
提问于 2016-07-14 23:34:17
回答 1查看 2K关注 0票数 3

我是一个新的Rails开发人员,并开始使用Rails 5中的ActionCable创建聊天应用程序。

问题是互联网上有很多使用ActionCable的聊天例子,但它们都很简单。它们创建一个通道,所有连接到该通道的用户都可以发送或读取来自他人的消息。

例如,他们创建了这样一个聊天频道:

代码语言:javascript
复制
class ChatChannel < ApplicationCable::Channel
  def subscribed
    stream_from 'messages'
  end

  def speak(data)
    ActionCable.server.broadcast('messages',
      message: render_message(data['message']))
  end

  private

  def render_message(message)
    ApplicationController.render(partial: 'messages/message',
                                 locals: { message: message })
  end
end

在客户端,他们连接到那个通道

代码语言:javascript
复制
App.chat = App.cable.subscriptions.create "ChatChannel",
  received: (data) ->
    $('#messages').append(data.message)

  speak: (msg) ->
    @perform 'speak', message: msg

如何在两个用户之间创建每个会话的频道?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-23 02:44:19

唯一改变的是你订阅的频道。在这种情况下应该是一个特定的对话。你可以有这样的东西:

messages.coffee

代码语言:javascript
复制
$(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();

messages_channel.rb

代码语言:javascript
复制
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

messages_controller.rb

代码语言:javascript
复制
# 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
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38385803

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档