首页 > 解决方案 > 如何修复 ActionCable 不附加数据

问题描述

我正在为我在 Rails 中的聊天室频道设置 ActionCable。

问题是每次登录用户发送消息时,比如 UserA,消息都不会附加到聊天室。我曾尝试同时登录另一个用户,比如 UserB,来自 UserB 的消息被附加到 UserA 的聊天室,但不是 userB,反之亦然。

/app/channels/chatroom_channel.rb

class ChatroomChannel < ApplicationCable::Channel
  def subscribed
    stream_from "chatroom_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end

end

/app/assets/javascripts/channels/chatroom.coffee

App.chatroom = App.cable.subscriptions.create "ChatroomChannel",

connected: ->
# Called when the subscription is ready for use on the server

disconnected: ->
# Called when the subscription has been terminated by the server

received: (data) ->
  alert data
  $('#messages').append(data)
  $('#message_content').val = ''
  scrollToBottom()
  return

scrollToBottom = ->
  if $('#messages').length > 0
    last_message = $('#messages')[0]
    last_message.scrollTop = last_message.scrollHeight - (last_message.clientHeight)

$(document).ready ->
  scrollToBottom()
  return    

jQuery(document).on 'turbolinks:load', ->
  scrollToBottom()
  return   
  # Called when there's incoming data on the websocket for this channel

这是我的聊天室视图的一部分:/app/views/chatrooms/index.html.erb

<div class="twelve wide column">
  <div class="ui fluid raised card chatbox">
    <div class="content">
      <div class="ui feed" id="messages">
        <%= render @messages %>
      </div>
    </div>
    <div class="extra content">
      <%= form_for(@message, html: {class: "ui reply form", role: "form"}, url: message_path) do |f| %>
        <div class="field">
          <div class="ui fluid icon input">
            <%= f.text_field :body, id: "message_content"%>
            <%= f.button '<i class="bordered inverted orange edit icon"></i>'.html_safe %>
          </div>
        </div>
      <% end %>
    </div>
  </div>
</div>

我已将开发从更改asyncredisin,config/cable.yml但仍然没有成功。感谢您提前阅读

标签: ruby-on-railsactioncableruby-on-rails-5.2

解决方案


推荐阅读