ruby-on-rails - 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>
解决方案
推荐阅读
- python - 我可以在 MacOS 上使用 Keras ImageDataGenerator().flow_from_directory 跳过文件吗?
- scala - 斯卡拉
.reduce 泛型类型的奇怪行为 - java - Spring Boot 测试 HttpMessageNotReadableException
- python - 如何在 ndarray 中找到最常见的元素
- c# - 通过 selenium 启动时如何处理边缘浏览器上的警报
- jenkins - 如何在 Jenkins 中执行同时构建?
- javascript - 如果其中一个值匹配,则将对象的值合并到一个新数组中
- swift - 尝试在领域中编辑列表
- haskell - Haskell:无法构造无限类型:t ~ t -> t
- java - Spring Data JPA 规范调用