User Notifications

Episode #136 by Teacher's Avatar David Kimura

Summary

Using the Notifications Rails Engine, we are able to add notifications to our applications based on certain events. The engine provides the schema and necessary controls and associations to seamlessly integrate into your app.
rails notifications engine 13:08

Resources

Download Source Code

Summary

# Terminal
rails g notifications:install
rails db:migrate

rails g notifications:controllers
rails g notifications:views

# Gemfile
gem 'notifications'

# layouts/application.html.erb
<div class='container'>
  <ul class='navigation'>
  <% if user_signed_in? %>
    <li><%= link_to pluralize(Notification.unread_count(current_user), 'Notification'), notifications_path %></li>
    <li><%= link_to current_user.email, main_app.edit_user_registration_path %></li>
    <li><%= link_to 'Logout', main_app.destroy_user_session_path, method: :delete %></li>
  <% else %>
    <li><%= link_to 'Login', main_app.new_user_session_path %></li>
  <% end %>
  </ul>
  <%= yield %>
</div>

# models/comment.rb
class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :user

  after_commit :create_notifications, on: :create

  private

  def create_notifications
    Notification.create do |notification|
      notification.notify_type = 'post'
      notification.actor = self.user
      notification.user = self.post.user
      notification.target = self
      notification.second_target = self.post
    end
  end
end

# views/notifications/_post.html.erb
<div class=''>
  <%= link_to notification.actor.email, main_app.user_path(notification.actor) %> has commented in
  <%= link_to notification.second_target.content, main_app.user_post_path(notification.user, notification.second_target) %>
</div>

<div class=''>
  <%= notification.target.content %>
</div>

# db/routes.rb
  mount Notifications::Engine => "/notifications"