我正在创建一个ruby应用程序,我正在尝试实现动作电缆,当用户发帖时,我希望为所有用户更新帖子索引。在我的频道/ posts.js中我有:
App.posts = App.cable.subscriptions.create("PostsChannel", {
connected: function() {
// Called when the subscription is ready for use on the server
},
disconnected: function() {
// Called when the subscription has been terminated by the server
},
received: function(data) {
// Called when there's incoming data on the websocket for this channel
console.log(data)
$('#list').html("<%= escape_javascript render('list') %>")
}
});
PostRelayJob.rb中的我有:
class PostRelayJob < ApplicationJob
queue_as :default
def perform(post)
ActionCable.server.broadcast "posts",
post: PostsController.render(list)
# Do something later
end
end
并在models / post.rb中:
after_commit { PostRelayJob.perform_later(self) }
当我在服务器控制台中添加帖子时,我得到:
[ActiveJob] [PostRelayJob] [57126ec7-b091-48fc-91aa-2f940caa9421] Performing PostRelayJob from Async(default) with arguments: #<GlobalID:0x00000003aa10d8 @uri=#<URI::GID gid://today-i-have2/Post/15>>
[ActiveJob] Enqueued PostRelayJob (Job ID: 57126ec7-b091-48fc-91aa-2f940caa9421) to Async(default) with arguments: #<GlobalID:0x000000037af000 @uri=#<URI::GID gid://today-i-have2/Post/15>>
[ActiveJob] [PostRelayJob] [57126ec7-b091-48fc-91aa-2f940caa9421] Performed PostRelayJob from Async(default) in 3.66ms
Rendering posts/create.js.erb
Rendered posts/_list.html.erb (7.5ms)
Rendered posts/create.js.erb (9.0ms)
然而,其他浏览器中的帖子没有更新,我对rails很新,所以任何帮助都会非常感激。
答案 0 :(得分:0)
首先,您似乎在传递整个列表而不是仅添加每个新项目。如果你想按照你的方式去做,我相信你的问题出在你的JS中。你需要jQuery删除你的旧列表,jQuery添加你的新列表。您可以通过为列表创建容器来完成此操作:
<div id="list-container">
Whatever HTML has the id "list" here
</div>
然后当您收到数据时:
received: function(data) {
// Called when there's incoming data on the websocket for this channel
console.log(data)
$('#list').remove
$('#list-container').append(data)
}
答案 1 :(得分:0)
我认为这种行为是出现在在Rails控制台中创建Post对象的情况下。它在很大程度上取决于您的ActionCable配置,但我认为您没有在开发环境中使用Redis。
开发环境的默认配置是使用async
适配器。此适配器仅在同一进程中工作。要启用跨进程通信,您需要备用适配器。
我的建议是安装Redis(例如通过brew redis
),使用redis-server
启动它并使用以下命令更新config / cable.yml:
development:
adapter: redis
url: redis://localhost:6379