3

서버를 다시로드하지 않고도 데이터베이스의 변경 사항을 페이지에 반영하고 싶습니다.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> 

.

데이터베이스에서 제품을 업데이트 할 때 변경 사항이 웹 페이지에 반영되지 않습니다.

무엇이 누락 되었습니까?

답변

2

레일스는 실시간으로보기를 업데이트 할 수 없습니다. 그것은 HTML을 제공하고 스트림을 듣고 이벤트를 처리하기 위해 자바 스크립트를 사용합니다.

나는이 모든 것을 처리하는 보석 인 Shower를 만들었습니다. 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 

그런 다음 이벤트 스트림을 듣고 그에 따라 행동해야하는 자바 스크립트가 필요합니다.

$ -> 
    stream = new Shower('/stream', ['product.update']) 

    stream.addEventListener('product.update', (event) -> 
     product = JSON.parse(event.data) 
     $('p').html(product.price) 
    ) 
+1

Redis는 현재 내 스택에는 없습니다. 이 기능을 작동시키기 위해 특별히 설정해야 할 부분이 있습니까? @KPheasey – softcode

+0

샤워가 생성되는 것처럼 보입니다. 경로 --- get '/ stream', : 'shower/stream # index'--- 스트림이/stream으로 스트리밍 되었습니까? 그렇다면 페이지 방문시 Rails에서 "고정 된 해시를 수정할 수 없습니다"@KPheasey – softcode