首页 > 解决方案 > Rails 5从ajax请求订阅Action Cable频道

问题描述

我一直在尝试仅通过 ajax 请求显示所有对话消息而不刷新页面。使用此代码,我可以使用频道发送消息,但我无法接收消息。

我想从前端动态传递 ID。我知道可以通过将 data 参数添加到 body 标签中来实现这一点(像这样)。

我也想做同样的事情,但是当我点击一个更改正文数据“conversation-id”的对话并订阅新的频道 id 时。我希望可以使用 rails 5/jquery(ajax) 来实现。

这是我的代码:

对话.咖啡

App.conversation = App.cable.subscriptions.create channel: "ConversationChannel", id: document.querySelector('#conversation').dataset.conversationId,
  connected: ->
    $('#new_message').submit (e) ->
      $this = $(this)
      id = $this.find('#message_conversation_id');
      body = $this.find('#message_body')
      App.conversation.write id.val(), body.val()
      body.val('')
      e.preventDefault()
      return false

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

  received: (data) ->
    $('.box-msg').append(data.data)

  write: (id, body) ->
    @perform 'write', {id: id, body: body}

对话频道.rb

class ConversationChannel < ApplicationCable::Channel
    def subscribed
      id = "[HOW CAN I PASS DYNAMICALLY ID]" 
      if id #on stream seulement si id existe
        stream_from "conversation_#{id}"
      end
    end

    def unsubscribed
      # Any cleanup needed when channel is unsubscribed
    end
    def write(data)
        msg = Message.create(
          conversation_id: data["id"], 
          body: data['body'], 
          user_id: 41,
          read: 0
        )
        if msg.save 
          html = ApplicationController.render(partial: 'messages/message', locals: { message: msg})
        end
        ActionCable.server.broadcast "conversation_#{data["id"]}", data: html
    end
  end

对话/index.html.erb

<script>
    $(document).ready(function() {
        $('.card-conversation').click(function() {
            $("#conversation-content").html('');
            var id = $(this).data("conversation");
            $("body").attr("data-conversation-id", id);
            $("#message_conversation_id").val(id); //input id 
            $.ajax({
                url: "/conversations/"+id+"/messages",
                cache: false,
                success: function(html){
                    $("#conversation-content").append(html);
                }
            });
            $("#conversation-content").fadeIn();
        });
    });
</script>
<div class="row h-100 no-margin">   
    <div class="col-md-4 h-100 messages-list" style="padding-right: 2px !important;">
            <% @conversations.first(3).each do |conversation| %>
                <div class="card card-conversation" data-conversation="<%=conversation.id %>">
                   <p>see conversation</p>
                </div>
            <% end %>
    </div>

    <div class="col-md-8 conversation no-padding" id="conversation">
        <div id="conversation-content"></div>
          <%= simple_form_for Message.new, url: "#" do |f| %>
              <%= f.input :body, label: false, placeholder: "Add msg" %>
              <%= f.input :conversation_id, label: false %>
              <%= f.submit 'Go' %>
          <% end %>
    </div>
</div>

标签: ruby-on-railsactioncable

解决方案


推荐阅读