ActionCable没有更新页面

问题描述:

我创建了一个ruby应用程序,我试图实现操作电缆,当用户发布帖子时,我想要为所有用户更新帖子索引。在我的频道/ posts.js我有:ActionCable没有更新页面

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 

和型号/ 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) 

Howe在其他浏览器的帖子没有更新,我很新的轨道,所以任何帮助将不胜感激。

首先,你似乎传递了整个列表,而不是只追加每个新项目。如果你想这样做,我相信你的问题在你的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) 
} 

我觉得这种行为出现在您的创建安置自己的对象的情况下在您的Rails控制台中。它很大程度上取决于您的ActionCable配置,但我认为您没有在开发环境中使用Redis。

开发环境的默认配置是使用async适配器。此适配器只能在相同的过程中使用。要启用跨进程通信,您需要一个备用适配器。

我的建议是安装Redis的(例如,通过brew redis),用redis-server启动它,并更新你的配置/ cable.yml:

development: 
    adapter: redis 
    url: redis://localhost:6379