Skip to main content

77 In-App Navbar Notifications

Episode 96 · December 5, 2015

Learn how to add in-app notifications like Facebook and Twitter

Notifications Javascript


What's up guys, this episode we're going to talk about In-App Notifications, because this is a feature I get requested almost every single week, so I thought it's about time we cover this. So what I'm talking about are those little notifications in the navbar that you usually see, and when you click on them you'll see the number, and you'll be able to mark them as read when you read them, and also they'll have links that will take you to the thing that created the notification.

For example, in GoRails, mine is really simple, it needs some cleanup, but it's just a navigation item that generates a menu that links to forum questions, so anybody that posts a question in there, you receive a notification, or if you join a discussion, you'll automatically be subscribed to the comments for that thread. This is what we're going to be duplicating today, I'm going to talk about how we do this, we're going to load this with AJAX, so we'll create the database models, we'll add them to the record so that when you take an action, if you would like to notify the users, I'll show you how to create the record; and we'll also build the JavaScript functionality to load these through AJAX so your page can load quicker, it can load the notifications after the page does, just like Facebook does, and then we'll also use JavaScript to mark them as read, and then you're going to have a perfect foundation to pull these URLs for notifications every three seconds so that you get relatively real-time notifications if you would like and go ahead and do that, so we're going to talk about all of that in this episode so let's get started.

What goes into creating a notification? Well, you've probably seen a lot of these things, such as: Bob liked your photo on Facebook, or you might see: "Anthony shared a link on your wall" or "Suzy commented on your post", you're going to see a lot of these, various things where there's an action taken on some object, and all of these just have a user that took an action on something, and this one is actually a link, rather than your wall. So this is building a sentence that links to something and tells you a bit about who did what, and it's very generic. With that in mind, we can create a model to represent that in our database

We're going to call it "Notification" of course and we're going to have five or six different fields of this (try to keep up):

1. recipient_id:integer
The user who gets the notifications

2. actor_id:integer
The user who took the action

3. read_at:datetime
Field that can tell the user or the website that the notification has already been read

4. action:string
Event that was recorded

5. notifiable_id:integer
Part of the notifiable object

6. notofiable_type:string
Part of the notifiable object

You have to have a way of differentiating between the user that recieves the notification and the one who generated it, in this case, I chose to go with recipient and actor, and to intentionally not use user because it's too vague; but you're free to name it user or something else if it's clearer for you

For the read_at you could also use booleans, but it doesn't really give you much useful information, read_at also may be a useful thing where you could set up functionality that maybe will email the user if they haven't read the post after three hours or something. This could help you a little bit with that, but in any case, read_at as datetime also helps you do analytics in the future, but you're only really treating it like a Boolean column you because you know the time that they read it at.

All that aside, the last piece that you really need is the action, and that will be commented, shared, liked, whatever... That will just be a simple string, and then you need the trackable item, so you're going to use a polymorphic association for this because as you can see, there's photos, links, posts, so on. The list will probably will continue growing, but it's always going to be notifications for a vast number of different things. You don't need to create post notifications and link notifications and separate those because that would just get very confusing, this is where polymorphic associations come into play again, just like we talked about in our comments episode in the past.

Here we have some sort of object that is the notifiable object, if we call it notifiable_id and notifiable_type, those two can comprise the polymorphic association for notifiable, and that will be the object that you're linking to when someone clicks the notification. That's all you need in order to run the notification model,

We run:

rails g model Notification recipient_id:integer actor_id:integer read_at:datetime action:string notifiable_id:integer notifiable_type:string

rake db:migrate

And then jump into the model to set up the associations and then create those records anytime we need to in the create action. Adding those associations into the model is pretty simple:


class Notification < ActiveRecord::Base
    belongs_to :recipient, class_name: "User"
    belongs_to :actor, class_name: "User"
    belongs_to :notifiable, polymorphic: true

This will set up your associations for the notification, and then you can also have the has_many :notifications in the user model and then this is going to take the option because it needs to be linked as the recipient on the has_many, and that way you need link that, it will automatically look for User, and that won't work because there is no user association, so we have to specify an option here to link to the recipient and this is as simple as adding foreign_key: recipient_id to the has many notifications, and that will take care of that. With that in mind, we can go to our forum_posts_controller.rb and add creating of notifications into that.

When you're browsing a forum, you are browsing a thread and you're know the answer to somebody's question, and you type a message and click "Create Forum Post", that would take you to this action (create), it would create a new post in the thread, it would associate it to you and then save the post. Now here's where we need to create the notifications before the users. Now there's one trick to this that you have to be careful with, but we'll talk about that in just a second, first we need to just create the association to get all the users in the thread. We have one user, and if I post, I'll be another user, so we need some association on the forum thread to get all the users, and that's going to be rally simple:

has_many :users, through: forum_posts

because the forum posts belong_to :user we can grab those users on the thread. This will allow us to create the notification in the forum_posts_controller

@forum_thread.users.each do |user|
    Notification.create(recipient.user, actor: current_user, action: "posted", notifiable: @forum_post)

For each user we'll create a new notification with that user as the recipient, and that's pretty cool, because that allows us to loop through all of those users, notify everybody, and then redirect the user back, and this will be really fast because we're just creating a handful of records in the database, we're not actually sending out emails or anything, which you would want to do in a background job like the previous episode on sidekick.

The other options that we need to pass in for the notifications are the actor, so we'll pass in the current user as the actor, because you're logged in, you clicked "Submit", so you're the one that made the post, and that means you would be current user, and then the action will be "posted", and then we'll have the actual notifiable object, the thing we'll want to link to when you click on the notifications, that's why we're linking that instead of the thread, and that's all you have to do to create those notifications. The important thing that I mentioned we would talk about is that there's a little trick to this, because @forum_thread.users is not actually what you want, because this is going to get you everybody, and because you just created a thread, or a post in the thread, that will include you and that's not what you want, because you would get a notification as well if someone posted twice in the thread, they would get notified twice, so you want to call unique method on this to get the unique users, no duplicates and then you also want to remove an array of current_user:

(@forum_thread.users.uniq - [current_user]).each do |user|

If you're ever subtracting two arrays, you need to take the first array, which unique should return and then remove an array of these items, which is just one, which is your user. That should give you a unique array, and we should be able to jump into our application, click "Submit", everything worked fine, and then in the console and look at Notification.all and see if we got multiple notifications or if it worked right.

I was logged in as user number two, and you can see the actor_id is 2, it's not read, (which is good), posted the post number 6 and this is a notification for recipient user number 1. So that worked correctly.

excid3 is user number one and Chris is user number two and when Chris posts, excid3 get a notification but Chris does not, and then if I go in here and make another post and we submit that, then we should see a new notification, and I still haven’t gotten duplicate notifications as Chris.

This is something that you can use pretty much in any location that you would like you would be able to take this notification line and then pass this around and put it maybe in the forum thread, maybe you want it on likes, or maybe you want it on sharing photos. Anything like that, you have the freedom to take this line of code and reproduce it pretty much anywhere you would like to add notifications into your app. You can take this and move it around and use it in multiple places, which is pretty useful. Now that we have our notifications on our database, what do we actually do with them? How do we get these notifications into the UI and make it something that's flexible?

If you're building notifications, I would recommend building a notifications endpoint for JSON so I would make a sort of notifications resource, maybe you would consider even a little API in and of itself for your JavaScript to access it. One thing that you would have to do every single time that the page was loaded was look if the users signed in, and then display the notifications in the navbar, but that's one of those things that could be deferred into JavaScript and that would be totally fine.

That's what we're going to do, we're going to load those notifications with JavaScript and we're going to provide that with a resources :notifications in our routes file, so we're going to have

resources :notifications

We're just going to use the index there but we'll define that in our controller, so we'll open up:


class NotificationsController < ApplicationController
    def index 
        @notifications = Notification.where(recipient: current_user)

We need to make sure that the user is logged in

We will load up the notifications and then we'll probably want to limit those, so we probably want to only do maybe the unread notifications in the navbar so we can use the scope called "unread" for notification. If we open up models/notification.rb:

scope :unread, ->{where read_at: nil}

That's all you need to do to make a nifty little notification controller, so we'll load up all the unread notifications for the current user, and then we'll return some JSON for that. If we make a directory for app/views/notifications we can edit app/views/notifications/index.json.jbuilder, and here we're going to have to design our json that we're going to return to the JavaScript, and there's going to be a few helpers that we can do in here that make creating the links easier, for example. And we'll go through the notifications array, and pull out some JSON for each of those. So we can use the jbuilder helpers here and pass in the notifications and a block that takes each one of the notifications themselves and then we'll have our various things here so we'll have:


json.array! @notifications do |notification| 
    json.recipient notification.recipient 
    json.action notification.action 
    json.notifiable notification.notifiable 
    json.url forum_thread_path(notification.notifiable.forum_thread, anchor: dom_id(notification.notifiable)) 

The url line will generate the path to the forum thread and then take us down to the notifiable forum post so that will be a little shortcut to help us generate this URL, we'll do it in Rails, then our JavaScript doesn't have to worry about trying to build urls. Our JavaScript can just simply take the url and then put it in the html. To test and see if this is working, we just want to open up the /notifications.json url in our browser and we should get a json response back, but because we're logged in as Chris instead of excid, I don't have notifications on this user account but our other user does. So let's just log out and log back in, and then check this out from the other users perspective,

If we open that up now, we can see that there is are two notifications here with the JSON related to it, so you'll see the recipient, you'll get some information about the recipient, it might just easier to pass in the username for the recipient, because we're going to be linking to the post itself and not the user. If you add more complicated formatting, you could pass in this extra data, but we're going to keep it simple an only link to the URL that we added at the bottom.

Let's adjust that (already adjusted in the code block above). The recipient we might actually may not need to include this whatsoever because we know that it's for you, so we can comment this out or just delete it, and simplify our JSON response a lot. Now the other thing you might have noticed is that we have:


So we've got this really big piece of JSON here that's every attribute about the notifiable object. We don't need all that stuff because it doesn't make it easy for us to say Chris posted a comment in a thread or something like that. It doesn't help us really easily pull that out. So I would recommend modifying your JSON to do something that's more flexible, so we have this notification notifiable object array, and we can simply add a type:

json.notifiable do #notification_notifiable 
    json.type "a comment"

So you can have your JavaScript really easy put the actor, action and the type together and say that Chris posted a comment, that would be much much easier for your JavaScript to put together in the notification and then combine these, if you ever wanted to say that Chris and Bob posted a comment, then you could combine those nicely.

This is the design of your JavaScript and your JSON, you want to make it easy for you to write simple JavaScript because there's going to be a bunch of different types potentially:

  1. you liked a photo
  2. you shared a link
  3. you commented on a status

all of these are going to be different, and if you give it a really basic format here, then your JavaScript can just run through these, and it is really fast. And it doesn't have to know as much about the server side stuff which is a huge huge improvement, so wouldn't it be nice if you could just take the notifiable thing and said Chris posted a forum post? We could actually interpolate a string here and say

json.type "a #{notification.notifiable.class.to_s.underscore.humanize.downcase}"

The methods above converts

ForumPost to forum_post to Forum post and finally to forum post

And that allows us to automatically generate a forum post as the type string which is awesome. This way, you can pass in any type of object and as long as it had a reasonable name as your model name, then if you add photo or user, all of those would be converted dynamically into a nice readable string that you JavaScript can render and that is probably what I would suggest. Now the next piece that we need to think about in our JSON data structure is what you're going to do for marking these as read. Personally, I want to make this work like Facebook and Twitter, where you click the notifications here at the top and might have a number next to it when I make it so that when you click that it would remove the number and mark all those as read. That's going to be as simple as when you click it, it will send a mark as read thing to the server, and that means that you don't need to include the id's of the individual items as arguments to that, because you're marking everything as read, but if you ever want to mark individual items as read, you can just say and that will add the ID number into each of these which might be useful to pass in anyways, that will allow you to reference specific notifications from your JavaScript.

Digital Ocean has notifications, you can mark individual ones as read or not, so you can pass in the id's if you ever want to build functionality like that. That's pretty cool, and you have complete control to customize this to however you want this experience to work.

The other thing we need to do is we're going to need to make a POST request for the notifications that allows us to mark them as read.

If we do everything, we can do a collection action, we can make a mark as read action, and then that would map to the notifications controller and a mark as read method, and we're going to look for the notifications where recipient is the current user, and we're going to want the unread ones just like before, and this time, we're going to update all and we're going to read at the recipient's time zone and you can render json back and signal that success is true


resources :notifications do 
    collection do 
        post :mark_as_read


def mark_as read 
    @notifications = Notification.where(recipient: current).unread 
    render json: {success: true}

In the section of the video Chris makes a typo, and corrects it later on, it's already corrected in this transcript, to save you some annoyance

You'll use HTTP response codes if it fails, and then if it's successful then they will have the 200 back and then also have a little data in the JSON to parse and see if it was successful or not. So that is as simple as that. It's going to mark all of those as read and that's it. Now we need to connect the JavaScript to the front end, so we need to load up the JavaScript when you view this page, display the notifications here and then we need to go ahead and mark those as read. To create the HTML to interact within the JavaScript, I'm just going to paste in some example code that I've found for bootstrap 4 alpha. This isn't going to be the prettiest, because bootstrap 4 is still alpha so the dropdowns don't actually align properly which you'll see in a second, but this is sort of what you're html will look like for notifications. If we save this and just refresh the page, you're going to see the notifications show up in the navigation, and you'll see them show up when you click on the dropdown. These are hard coded, and we're going to need load those up dynamically on the page load.

This is working, and that's basically what we want, but now we need to make it dynamic.

We're going to create a file in app/assets/javascripts/

The html is set up to only run if the user is signed in, so we're only going to see the notification bar when the user is signed in which is good because then we can load the JavaScript for it only if this is on the page.

We will need a new class in CoffeeScript called notifications and in the constructor, we'll set it up so that we'll only call the setup method if there's the notifications on the page. Now I'm going to use the data behavior stuff that I've talked about in the past, and the length should be greater than zero if it's actually on the page.

We will also create a setup method when it's actually available and then we'll be able to reference that. That means that we're going to need data-behavior="notifications" over in the html and that should make it referencable there

You can test that your browser is actually detecting the notifications if you console.log your notifications in the JavaScript. If you see a jQuery array, you're good to go.

Using jQuery to make an AJAX request to the notifications.json url, the data type is json and it's a get request and on success, we can call a different method. (@handlesuccess).

For the handlesuccess method we can use a thick arrow so that we can reference the variables the same way as before and here, we'll have the code to actually get the data back. The first parameter that you'll get with this is the notifications in JavaScript format. If we refresh this page now, we can see the array notifications on the console printed out, but they've been parsed into JavaScript objects for us because of the AJAX request specifying the data type is JSON. So it parses those out into an array for us which is HANDY DANDY grin And we can map this array into a set of string that we can insert into the page.

If we take each notification here and we convert them into this anchor tag. Take the elements of the array (action, actor, notifiable type, url) and convert that into the html that we need to display

Up to this point, the JavaScript bit looks like this:

class Notifications
    constructor: ->
        @notifications = $("[data-behavior='notifications']")
        @setup() if @notifications.length > 0 

    setup: -> 
            url: "/notifications.json"
            dataType: "JSON"
            method: "GET"
            success: @handleSuccess

    handleSuccess: (data) =>
        items = $, (notification) ->
            "<a class='dropdown-item' href='#{notification.url}>#{notification.action} #{notification.notifiable.type}</a>"


jQuery ->
    new Notifications 

Since we want our own elements on the dropdown, instead of the hard coded ones (duh), we're going to add in the html the data behavior of notifications in the html in the dropdown menu div and if we didn't screw up, refreshing the page and clicking on the notifications should show us Chris posted a forum post. You might want to check out Chris's final code here, there are differences with the one written to this point in the video and also no errors, but I just transcripted it the way it is

The CSS is still a little broken and it goes off the page, but if we look at it, we're getting the dropdown items, they're linking to the correct place. If you click on them, they will take you to the thread and everything that you would expect out of your notifications.

Another cool thing that we could do here is add to the handleSuccess:


and if we add a span behind the bell that's data-behavior="unread-count", leave it empty by default. And if you refresh the page you can see that it's empty for a second and then it changes to two notifications that have been loaded and you are good to go.

The last piece of this puzzle is to clear out when you click on this dropdown, so when you click on it, we need to send a notification to the server to mark these as read so that next time that you load a page they don't show up.

We do the initial load in the setup, and the other thing that you want to do is to grab the anchor type that is the button type, add `data-behavior="notifications-link" and over in the javascript:

setup ->
    $("[data-behavior='notifications-link']").on "click", @handleClick

//some code 

handleClick (e) => 
    dataType: "JSON"
    method: "POST"
    success: -> 

You can check that out if you rake routes and see the POST request notifications/mark_as_read it is very important to notice that we're sending a POST request

This last bit of code that we added allows us to fire that request off to the server when you click on it, and if we do that, you should see in the network anytime this is clicked, you'll see a post-request go over at the bottom, anytime you click this you'll see the mark as read post request.

If we click this (And didn't make any typos), it should change to zero, and it does. Server side you'll see the POST request, to mark as read, and we'll update all those notifications and set the read at to the current timestamp. That's all that it takes to mark those as read and now you'll see that there are zero unread notifications and you could put in placeholder text, whatever you would like, all you would have to do really is to modify your file and put in some extra code around the handlesuccess. In a way that checks if the length of items is 0 and maybe you put in a different message like there are no new unread notifications, you can fully modify that here, this is just a good little class to handle that functionality and your JavaScript doesn't do very much of the UI, it just manipulates it as necessary.

This could be a really good episode that we could clone in react and see how this would interact with it. And really the backend of JSON API that we have for notifications probably would stay the same, you would just end up writing react instead of jQuery more or less.

If you're interested in seeing something like that in the future leave a note in the comments below and we'll get to that, if you guys really want to see it, I would love to do more react stuff anyways. That's basically the whirlwind tour for all the sort of things to think about when you're building notifications. Keep them simple, definitely don't try to overdo it. Don't tailor them too closely to specific things, try to keep them generic because you know that you will use that in other places in your application in the future, things are bound to change, so if you can make things sort of generic and sort of simple at the same time, then awesome thumbsup, you have foundation for notifications that you could probably pull out even into a gem that you could reuse, maybe this is something that you guys would like to see as a gem. I dunno, let me know, until next time, I will talk to you next week, peace v

Transcript written by Miguel