Our Rails App and Redis Communication

Our Rails app talking to Redis

Although it is great that we have started up a Redis server using Compose, it is not much use to us by itself. The whole point of running the Redis server is so our Rails app can talk to it and use it as a key-value store. So let’s connect our Rails app to Redis and actually use it for something.

There are a million ways an app might want to use Redis. For our purposes, though, we do not really care what we use Redis for: we care more about how we use it. We are intentionally going to use a basic example. Our Rails app will simply store and retrieve a value. However, keep the larger point in mind: once you know how to set up the Rails app to talk to the Redis server in a container, you can use it however you like. Ready? Let’s begin.

Installing the Redis gem

The first thing we need to do to get our Rails app talking to Redis is to install the redis gem. You may remember that to update our gems, we need to update our image.

So first, in our Gemfile, the redis gem needs to be uncommented:

gem 'redis', '~> 4.0'

To build the custom Rails image:

$ docker-compose build web

Among other things, this runs bundle install that installs the Redis gem. It is good to get into the habit of rebuilding our image to perform bundle install for us, having updated our Gemfile. That said, we will learn about a more advanced approach to gem management, which will allow us to stick with our familiar bundle install workflow.

The following command builds and ups the Rails server again:

$ docker-compose up -d web

Updating our Rails app to use Redis

Next, we are going to actually use Redis from our Rails app. As we said before, we just want a basic demonstration that we can connect to the Redis server and store and retrieve values. To generate a welcome controller in our Rails app with a single index action, use:

$ docker-compose exec web bin/rails g controller welcome index

This will generate various files, and we will edit them according to our need.

File welcome_controller.rb

The file created in app/controllers/welcome_controller.rb looks like this:

class WelcomeController < ApplicationController
  def index
  end
end

Modification

It will be modified as follows:

Get hands-on with 1200+ tech skills courses.