ActionController::Live - 在Rails中使用SSE

3
我希望数据库的更改可以在页面上实时显示,无需重新加载服务器。
控制器
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。
当我在数据库中更新产品时,网页上没有反映出更改。
我缺少了什么?
1个回答

2
Rails无法实时更新视图。它提供HTML,然后需要一些JavaScript来监听流并处理事件。
我创建了一个叫做Shower的Gem,可以为您处理所有这些问题。 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)
    )

1
Redis目前不在我的堆栈中。我需要做任何特殊的配置才能让它工作吗?@KPheasey - softcode
1
你只需要在本地系统上安装Redis。在Mac上,可以通过Homebrew轻松安装,或者在Linux系统上通过包管理器进行安装。具体步骤请参考https://www.digitalocean.com/community/tutorials/how-to-install-and-use-redis。 - KPheasey
似乎Shower创建了一个路由 ---get '/stream', to: 'shower/stream#index'--- 流是否被流式传输到 /stream?如果是这样,在访问该页面时,Rails会报错:"Can't modify frozen hash" @KPheasey - softcode

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接