[英]ActionController::Live - SSE in 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>
我正在使用Puma。
當我更新數據庫中的產品時,更改不會反映在網頁上。
我錯過了什么?
Rails無法實時更新視圖。 它提供了html,然后由一些JavaScript來監聽流並處理事件。
我創造了一個寶石,淋浴,為你處理所有這些。 https://github.com/kpheasey/shower
使用Shower,解決方案就是這樣的。
首先,您需要發布更新事件,這可以通過Product模型上的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)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.