2016-09-16 65 views
2

我創建了一個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在其他瀏覽器的帖子沒有更新,我很新的軌道,所以任何幫助將不勝感激。

回答

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) 
} 
0

我覺得這種行爲出現在您的創建安置自己的對象的情況下在您的Rails控制檯中。它很大程度上取決於您的ActionCable配置,但我認爲您沒有在開發環境中使用Redis。

開發環境的默認配置是使用async適配器。此適配器只能在相同的過程中使用。要啓用跨進程通信,您需要一個備用適配器。

我的建議是安裝Redis的(例如,通過brew redis),用redis-server啓動它,並更新你的配置/ cable.yml:

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