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

相关问题