Rajesh Omanakuttan
Rajesh Omanakuttan

Reputation: 6918

How to dynamically and efficiently pull information from database (notifications) in Rails

I am working in a Rails application and below is the scenario requiring a solution.

I'm doing some time consuming processes in the background using Sidekiq and saves the related information in the database. Now when each of the process gets completed, we would like to show notifications in a separate area saying that the process has been completed.

So, the notifications area really need to pull things from the back-end (This notification area will be available in every page) and show it dynamically. So, I thought Ajax must be an option. But, I don't know how to trigger it for a particular area only. Or is there any other option by which Client can fetch dynamic content from the server efficiently without creating much traffic.

I know it would be a broad topic to say about. But any relevant info would be greatly appreciated. Thanks :)

Upvotes: 0

Views: 319

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

You're looking at a perpetual connection (either using SSE's or Websockets), something Rails has started to look at with ActionController::Live


Live

You're looking for "live" connectivity:

"Live" functionality works by keeping a connection open between your app and the server. Rails is an HTTP request-based framework, meaning it only sends responses to requests. The way to send live data is to keep the response open (using a perpetual connection), which allows you to send updated data to your page on its own timescale

The way to do this is to use a front-end method to keep the connection "live", and a back-end stack to serve the updates. The front-end will need either SSE's or a websocket, which you'll connect with use of JS

The SEE's and websockets basically give you access to the server out of the scope of "normal" requests (they use text/event-stream content / mime type)


Recommendation

We use a service called pusher

This basically creates a third-party websocket service, to which you can push updates. Once the service receives the updates, it will send it to any channels which are connected to it. You can split the channels it broadcasts to using the pub/sub pattern

I'd recommend using this service directly (they have a Rails gem) (I'm not affiliated with them), as well as providing a super simple API

Other than that, you should look at the ActionController::Live functionality of Rails

Upvotes: 1

SreekanthGS
SreekanthGS

Reputation: 988

The answer suggested in the comment by @h0lyalg0rithm is an option to go.

However, primitive options are.

  1. Use setinterval in javascript to perform a task every x seconds. Say polling.

  2. Use jQuery or native ajax to poll for information to a controller/action via route and have the controller push data as JSON.

  3. Use document.getElementById or jQuery to update data on the page.

Upvotes: 0

Related Questions