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.
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. It serves the html and then it's up to some JavaScript to listen to the stream and handle the events.
I've created a gem, Shower, that handles all of this for you. https://github.com/kpheasey/shower
Using Shower, the solution would be something like this.
First you need to publish the update event, this can be done with an after_update callback on the Product model.
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.
$ ->
stream = new Shower('/stream', ['product.update'])
stream.addEventListener('product.update', (event) ->
product = JSON.parse(event.data)
$('p').html(product.price)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With