Developer Diaries — 05

Derek Le
4 min readJan 10, 2022

One of the newer functionalities that I’ve added to my Tablecloth app was websockets to provide live updates to menu items. This would allow multiple instances of my app to subscribe to changes in my backend and display those changes on the frontend automatically.

Today, I’d like to walk through how I went about setting things up.

01 Setting Up Our Database

Starting with our backend, we’re going to run

rails new backend --api --no-test-framework

Next, we will need to create some resources for us to fill our database with.
For my app, I structured it as a store that contains many products that users can create.

rails g scaffold store name --no-test-frameworkrails g scaffold product name store:references --no-test-framework
rails db:migrate

For the sake of this example, let’s seed our database so we have some information to work with.

Navigate to /backend/db/seeds.rb

I’m going to create a store and a single product that will belong to that store.

Store.create({name: ‘test-store’})Product.create({name: 'test-product', store_id: 1})
rails db:seed

We can find out that our seed was successful by diving into the rails console with rails cand querying all Store and Product objects with Store.all and Product.all.

That does it for setting up our database. Next, we will need to do some additional configurations for our backend.

02 Configuring the Backend

Opening up our gemfile, we will want to enable rack-cors since our app will be enabling users to make changes to our database from the front-end.

Then, we need to navigate to /backend/config/initializers/cors.rb and uncomment the block of code provided to us. We also need to change origins from ‘example.com’ to ‘*’ (appropriate for development purposes only, as this can be a huge security issue on deployment.)

With this, this should complete the initial setup of our backend.

03 Setting Up Channels

Next we will need to create channels for our websockets to listen in on for changes in our database. Let’s go ahead and run the following:

rails g channel store

This will create a new file, /backend/app/channels/store_channel

Add the following lines:

Then, we will need to navigate to our /config/routes file and add our actioncable server.

mount ActionCable.server => ‘/cable’

04 Building the Frontend

Navigating to our Project root folder in the terminal, go ahead and run

yarn create react-app frontend
yarn add actioncable --save

Then, let’s create a component for us to use. It will need a form to post data to our backend, and a way to render incoming updates from

Next, we need to create a consumer in index.js, and pass it down to our app. There are many ways to approach this, but we’re going to just pass it down through our <App/> props.

05 Displaying it all together

--

--