Having a notification system is very common for a web application. In this post I will go over how to implement your own simple and easy notification system for your Rails application.
This post is heavily inspired by Chris Oliver's In-App Navbar Notifications tutorial, with a few personal changes and additions.
Read part 2 of this series.
Models and Routes
Before starting with the models, lets quickly define the application resources in our routes:
resources :posts do
resources :notifications, only: [:index]
The Notification Model
We will manually generate the notification model which will handle the storing of notifications in the database. We can generate a very basic model like this:
rails g model Notification recipient_id:integer actor_id:integer read_at:datetime action:string notifiable_id:integer notifiable_type:string
Here is an explanation for some of the fields for the above model:
recipient_id: Represents the user in your application which will receive the notification.
actor_id: Represents the user in your application which triggered the notification.
read_at: The time when the notification was read. A value of
nil is used for unread notifications.
notifiable_id: The object that represents this notification (a post, comment, etc). This will be a polymorphic association.
notifiable_type: Type of the notifiable object. This is usually represented by a humanized (and optionally, internationalized) string form of the object's class.