3

我希望數據庫中的更改反映在頁面上而不需要重新加載服務器。ActionController :: Live - SSE在Rails中

控制器

class ProductController < ApplicationController 
    include ActionController::Live 

    def index 
    @product = Product.available 
    response.headers['Content-Type'] = 'text/event-stream' 
    sse = SSE.new(response.stream) 
    sse.write @product 
    ensure 
    sse.close 
    end 
end 

視圖

<p><%= @product[:price] %></p> 

我使用彪馬。

當我更新數據庫中的產品時,更改未反映在網頁上。

我錯過了什麼?

回答

2

Rails無法實時更新視圖。它服務於html,然後取決於一些JavaScript來監聽流並處理事件。

我創建了一個寶石,淋浴,爲您處理所有這些。 https://github.com/kpheasey/shower

使用淋浴,解決方案將是這樣的。

首先,您需要發佈更新事件,這可以通過產品模型上的after_update回調完成。

class Product < ActiveRecord::Base 
    after_update :publish_event 

    def publish_event 
     Shower::Stream.publish('product.update', self) 
    end 
end 

然後,您需要一些JavaScript來收聽事件流並對其採取行動。

$ -> 
    stream = new Shower('/stream', ['product.update']) 

    stream.addEventListener('product.update', (event) -> 
     product = JSON.parse(event.data) 
     $('p').html(product.price) 
    ) 
+1

Redis目前不在我的堆棧中。有什麼特別的配置,我必須投入到這個地方工作? @KPheasey – softcode 2015-01-27 01:38:17

+0

它看起來像淋浴創建一條路線--- get'/ stream',到:'shower/stream#index'---這個流是否流入/流?如果是這樣,在訪問該頁面時,Rails抱怨:「無法修改冷凍哈希」@KPheasey – softcode 2015-01-27 21:53:39

相關問題