2017-04-05 59 views
8

我非常困惑,這是我的第一個Faye或Pub/Sub實現,所以請原諒我,如果這是一個基本問題。我還沒有在其他地方找到答案。任何幫助表示讚賞。更新Rails視圖與Faye從數據庫更改(after_commit回調)在型號

如何從模型回調(after_commit,after_save等)調用和更新Rails視圖頁?我需要一個javascript代碼,在after_commit回調觸發後,視圖更新從views/meetings/_show_current_participants.js.erb運行。

我把它設置好了,如果我在視圖上使用帶有return => true的link_to標記,它就可以執行javascript並查看更新。事情是我將沒有任何用戶交互,並且需要將視圖更新推送到僅基於數據庫更改的頁面庫(因此在模型上after_commit回調)。這不正確的工具/設計模式/方法嗎?

我試着對after_commit回調進行HTTP獲取請求到http://localhost:3000/conferences/conference_id/_show_current_participants_url但是這並沒有觸發Faye/javascript在頁面視圖上執行。

這就是:_show_current_participants.js.erb

<% participant_broadcast "/conferences/#{@conference.id}" do %> 
    alert('_show_current_participants.js.erb loaded'); 
    $("#current_participants_js").html("<%= escape_javascript(render partial: 'conferences/show_current_participants.html', locals: { conference: @conference }) %>"); 
<%end%> 

這就像一個魅力,如果我將它設置爲上觸發的link_to標籤與遠程=>真:

<li><%= link_to "Faye CALL", "#{@conference.id}/_show_current_participants", remote: true %></li> 

哪有我修改了這個設置,所以不必點擊一個鏈接,就可以在after_commit模型回調中激活Faye和隨後的部分javascript。這是錯誤的方法?我還能如何根據數據庫更改告訴我的視圖進行更新?任何幫助表示讚賞。非常感謝任何願意幫助我找到正確方向的人。

版本:

王菲1.2.4(不是王菲護欄)
的Rails 4.1.5
的Ruby 2.3.0
在這一點上超過我在找的東西,工作的超級靚解決方案。

回答

0

你應該訂閱的消息與JavaScript回調:

<script> 
    $(function() { 
     // Create a new client to connect to Faye 
     var client = new Faye.Client('http://localhost:3000/conferences'); 

     // Subscribe to the public channel 
     var public_subscription = client.subscribe('/#{@conference.id}/_show_current_participants', function(data) { 
      $("#current_participants_js").html(data); 
     }); 
    }); 
</script> 

我從參考此代碼是採取和調整:

https://code.tutsplus.com/tutorials/how-to-use-faye-as-a-real-time-push-server-in-rails--net-22600