1

我期待創建一個異步渲染部分的作業,一旦我從後端數據庫中收集選定的資源。我這樣做是因爲我獲取的數據需要很長時間才能獲取,而且我希望能夠在收到數據後顯示這些數據。現在我的代碼看起來像這樣的工作:將HTML從作業渲染到Rails 5中的頁面上

class CommentsJob < ApplicationJob 
    queue_as: default 
    def perform(commenter_company) 
    @comments = Comment.where(company: commenter_company) 
    @html = CommentsController.render partial: "comments", assigns {comments: @comments } 
    end 
end 

我已經有_comments.html.erb部分集合起來。我還將隊列適配器設置爲異步,以便此作業確實在後臺運行,並在加載頁面後完成。

我成功地能夠獲取html並將其設置爲作業中的@html實例變量。

我的問題是:如何將這個@html內容放到已經渲染的頁面上?這可以從工作內完成嗎,還是我需要使用ActionCable/websockets來完成這項工作?提前致謝!

+0

這似乎是你應該使用JavaScript。我非常肯定地顯示你將需要一個硬刷新或某種類型的JS的部分。 –

+0

你將不得不實施一些緩存。你想要做的是預熱緩存。看到俄羅斯娃娃與鐵軌緩存 – bcd

+0

謝謝你們。我寧願不必刷新並在數據顯示在紅寶石中之後顯示數據,但我知道推送給客戶端不能按照我設置的方式完成。另外,如果沒有頁面刷新,不會使用緩存嗎? – bcan001

回答

2

我認爲最好是使用ActionCable,並在接收廣播消息時使用ajax渲染帶有js.erb的部分。即在/assets/javascript/channels/comments.js:

this.App = {}; 

App.cable = ActionCable.createConsumer(); 

App.comments = App.cable.subscriptions.create('CommentsChannel', { 
    received: function(data) { 
    this.renderComments(data); 
    }, 

    renderComments: function(data) { 
    $.ajax({ 
     url: "/comments/update_comments" 
     data: { data: data } // Depending on how you structure the data you received 
    }); 
    } 
}); 

在您的意見控制器,你可以做任何你在/評論/ update_comments方法與您接收到的數據需要那麼它會影響您的部分渲染。讓我們說它只會刷新@comments。您認爲這些文件可以使用這個update_comments.js.erb,它會刷新你的部分在給定的html元素:

//app/views/comments/update_comments.js.erb 
$('#comments_container').html("<%= escape_javascript(render partial: 'comments') %>"); 

你可能部分是這樣的:

<!-- app/views/comments/_comments.html.erb --> 
<% @comments.each do |comment| %> 
    <p><%= comment.user %>: <%= @comment.message %></p> 
<% end %> 

希望我解釋自己。

0

你可以做這樣的事情

ActionCable.server.broadcast(
    "comments_#{@comment.id}_channel", 
    view: ApplicationController.render(
    partial: 'comments/commment', 
    locals: { comment: @comment } 
) 
) 

而且在js

App.comments = App.cable.subscriptions.create(
    {channel: 'CommentsChannel', id: comment_id }, { 
    received: function(data) { 
    $('#comments').append(data.view); 
    },