[英]ActionController::Live - SSE in Rails
I want changes in the database to be reflected on the page without server reload. 我希望数据库中的更改能够反映在页面上,而无需重新加载服务器。
controller 调节器
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
view 视图
<p><%= @product[:price] %></p>
I am using Puma. 我正在使用Puma。
When I update the product in the database, the changes are not reflected on the webpage. 当我更新数据库中的产品时,更改不会反映在网页上。
What am I missing? 我错过了什么?
Rails cannot update the view in real time. Rails无法实时更新视图。 It serves the html and then it's up to some JavaScript to listen to the stream and handle the events. 它提供了html,然后由一些JavaScript来监听流并处理事件。
I've created a gem, Shower, that handles all of this for you. 我创造了一个宝石,淋浴,为你处理所有这些。 https://github.com/kpheasey/shower https://github.com/kpheasey/shower
Using Shower, the solution would be something like this. 使用Shower,解决方案就是这样的。
First you need to publish the update event, this can be done with an after_update callback on the Product model. 首先,您需要发布更新事件,这可以通过Product模型上的after_update回调来完成。
class Product < ActiveRecord::Base
after_update :publish_event
def publish_event
Shower::Stream.publish('product.update', self)
end
end
Then you need some javascript to listen to the event stream and act on it. 然后你需要一些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.