Rails 5 Actioncable Real-Time Notifications – Part 1 Setup

rails5 actioncable tutorial screen4 notification center

Today we are going to build Facebook like notifications using Rails 5 and its newest tool ActionCable.

facebook like notifications rails5

Before you start, please take a look at the demo, you will be able to see final result of our work.

Source code for the demo is available here .

DEMO INSTRUCTIONS

For demo open 2 windows:

1. https://notificator-rails5-example.herokuapp.com/

2. https://notificator-rails5-example.herokuapp.com/messages/new

side by side. While adding message look at the notification center.

Pretty Cool, hugh ? You will build the same thing in next hour.

Lets start setting it up.

Setup

Pre requisites:

– Rails 5
– Ruby ~2.3
– PostgresSQL (as a db for heroku – brew install postgres)
– Redis (as a streaming server  for heroku – brew install redis)
– chillin’ music
– smile 🙂

Seriously, please make sure you are using Rails 5 . To verify run:

rails -v

Verified? Great. Lets create new rails app and call in “notificator”

rails new notificator --database=postgresql

This should give you new Rails 5 app. We are ready to go.

For this application we will create 2 kinds of objects:

Notification – will be our object that will hold actual notifications of what happened.

Message  – will be our object that we will attach Notification to it, and create new Notification every time new message is created.

Hopefully that makes sense 🙂

Lets scaffold our resources. First starting with Notification. For purpose of this tutorial Notification will hold only one attribute: event . This attribute is a string.

Go to notificator directory and run:

rails generate  model Notification event:string

Let’s migrate database to get table for our notifications.

rails db:migrate

Note: In rails 5 we use rails for db:migrate instead of rake

Next we want to show our notifications, so lets generate controller with single index action:

rails generate controller notifications index

While we are  here, lets go to this controller, and make sure we can retrieve all notifications in the reverse order (from latest to oldest)

notificator/app/controllers/notifications_controller.rb

class NotificationsController < ApplicationController
  def index
    @notifications = Notification.all.reverse
  end
end

As you might see, everything is straightforward. We are getting all notifications in reverse order. (Getting all resources at once is not good for performance reasons, but for this demo, we will omit performance concerns)

Let’s continue. Now we want to create  our Message resource. Same way, only this time we are scaffolding not just a controller or a model, but everything. We also use body attribute that will hold content of the message. Go to the root of our app and run:

rails generate scaffold  Message body:string

And once again, lets  run database migrate to create a table:

rails db:migrate

Congrats, basic setup is done!

Lets move on to the actual coding.

Setting up Views

Since we got our notifications, its time to think how we are going to present them.

Lets create a partial that will hold single notification first:

notificator/app/views/notifications/_notification.html.erb

<li>
  <%= notification.event %>
  <span> <%= notification.created_at.strftime("%d %b. %Y") %></span>
</li>

Our notification is a list item, and contains time and actual event.

If you looked at the demo, you know that we also need couple more things like modal that will  hold all the notifications and red counter to show how many notifications are there.

Lets start with modal. We will call our modal – notification center. And it also will be a partial.

notificator/app/views/notifications/_notification_center.html.erb

<ul class="notificator">
  <div id="notificationContainer">
    <div id="notificationTitle">Notifications</div>
    <div id="notificationsBody" class="notifications">
      <ul id="notificationList">
        <%= render notifications %>
      </ul>
    </div>
    <div id="notificationFooter"></div>
  </div>
</ul>

Notification Center has  multiple containers, that look weird now, but it will be handy for us when we will style Notification Center using CSS in Part 2,  but for now this is our structure.

Goal of a Notification Center to render notifications, that’s what we specify in our partial.

You might ask, where are we going to show this notification center ?

Answer is – anywhere we want, but for this demo –  we will show it on the index page.

Lets’ do it! Let’s render notification center partial on the index view and pass our notifications to it.

notificator/app/views/notifications/index.html.erb

<%= render "notification_center", notifications: @notifications %>

Great! Now lets make sure when person goes to ‘/’ route, they see our list of notifications.

Go to notificator/config/routes.rb  and make following changes:

Rails.application.routes.draw do
  root to: 'notifications#index'

  resources :messages


  # Websockets resemble this URL
  # mount ActionCable.server => '/cable'
end

Also lets hook our notification creation to the creation of message. We are doing it, by putting after_commit hook to our Message model. What will happen – every time someone creates a message, notification will be created as well.

Here is how you can do it :

notificator/app/models/message.rb

class Message < ApplicationRecord
  after_create_commit { notify }

  private

  def notify
    Notification.create(event: "New Notification")
  end
end

Easy breezy! Congrats, we are done with another step, now lets take a look what we have.

Run server:

rails s

Lets create some messages now.

Go to http://localhost:3000/messages/new it should look like this:

rails5_actioncable_tutorial_screen_1

Create 2-3 messages, and then go to http://localhost:3000/ , you should see something like this:

rails5_actioncable_tutorial_screen_2

Pretty cool, but pretty boring, I know 🙂 Stay with me, fun part is about to start!

Lets go to the Part 2 and see how we can style those notifications:

Rails 5 Actioncable Real-Time Notifications  – Part 2 Styling Notification Center

Please post your questions into comment section.

If you like what you see please Subscribe to my blog. If you need help with your project, please Get In Touch.

Thanks for installing the Bottom of every post plugin by Corey Salzano. Contact me if you need custom WordPress plugins or website design.

Anatoly Spektor

IT Consultant with 6 years experience in Software Development and IT Leadership. Participated in such projects as Eclipse IDE, Big Blue Button, Toronto 2015 Panam Games.

Related Posts

Join the Discussion

Your email address will not be published. Required fields are marked *

Discussion

  1. von

    How do i call the instance variable @notifications even if i’m not on the notification index page. I have a partial on top of my page that is visible on all pages which i would like the counter to be seen. Thank you

    1. Anatoly Spektor

      Hey von!

      You need to set this variable in the controller so it is available. One of the ways would be to create a before_filter in ApplicationController where you set your @notificaiton, this way it will be available everywhere ( since other controllers inherit from ApplicationController)

  2. Ihor

    Thanks, Anatoly, great article! Seems like links to the next parts are broken 🙁

arrow