我希望在不重新加载服务器的情况下将数据库中的更改反射(reflect)在页面上。
控制者
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。
当我更新数据库中的产品时,更改不会反射(reflect)在网页上。
我错过了什么?
最佳答案
Rails 无法实时更新 View 。它提供 html,然后由一些 JavaScript 来监听流和处理事件。
我创建了一个 gem,Shower,它可以为您处理所有这一切。 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)
)
关于ruby-on-rails - ActionController::Live - Rails 中的 SSE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28157258/