Rails 5从ajax请求订阅Action Cable通道

时间:2019-03-15 22:21:30

标签: ruby-on-rails actioncable

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

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

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

这是我的代码:

conversation.coffee

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}

conversation_channel.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

conversations / 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>

0 个答案:

没有答案