Skip to main content

In-App Navbar Notifications Discussion

General • Asked by Chris Oliver

Thank you thank you thank you!


This is exactly what I was looking for!! Thank you so much!!! I'd love to see how you integrate React to this feature too.

Me too. I'm using React on the front-end.



Hi Chris, thanks so much for all your videos, I always enjoy them. I'm curious how you handle your testing, when you're working on implementing a feature like In-App Navbar Notifications do you use TDD or do you write tests at the end? If you do use TDD I'd love to see you implement a feature using it!


Great episode, Chris. A cleaner and easier way to set the type node in your jbuilder template would be to use Rails' built in I18n support. So instead of `"a #{notification.notifiable.class.to_s.underscore.humanize.downcase}"`, you can do:

`"a #{notifiable.model_name.human}"`

This is cleaner and easier, and ensures that if the model name changes, the change will be reflected in your entire app. For this to work you need to set the model name in your I18n file. So en.yml would have:

```
en:
activerecord:

models:
post: "post"
```

PS: I would love to see this in React.


React! Yes! Do it!
I've been learning React just this week but tying it to Rails is still a bit of a mystery to me. This would be a perfect example to port over that I would love to see.
Your videos are great, keep on rockin it Chris! Thanks.


You're the man Chris, great video!!!

Yes, I would love to see some videos about React, and I would love it even more if you packaged this into a gem!!!

Thanks again for all your great videos!


Awesome episode!
I'd also be super interested in learning how to port this to React!


Super cool Chris, thank you.
You're awesome! (as usual)


great video! Seeing it done in React would be great.


Very useful and good pacing/progression of arguments.

Two questions.
1) the onClick handler is going to go to an object, so the page is going to be refreshed anyways. To make a counter decrement by 1, several options are available: one is to check the object and find Notification with equivalent object_id and type and recipient = current_user and update that. The other is to have routing as member and have the coffee script call `url: "notifications/#{id}/mark_as_read` and update there. I am not sure of which avenue is better (I believe the second may be faster), nor the proper syntax to generate the notification id in the url

2) you mentioned polling. Websockets would be the best solution for one with a server. This has two caveats. As a user, I have seen notifications be browser tab-dependant (I use a lot and do not always get notifications); it is a worry. In an exploratory phase (i.e. no significant traffic numbers), one could reason: 'let the user decide'. what would be a quick and dirty way to have a fa refresh icon update the notification status?


Great !! Fore some reasons i had to add as: :notifiable to the User model in order to make the notifiable attribute to be recognised. Any idea ?


Im getting missing template error when going to the url /notifications.json

not sure why.....

Fixed the issue by adding the Jbuilder gem


hi! Thanks for the great post. There's a problem as I click on the bell icon all the notifications disappear. Can anyone please help me with that?


Hi Chris, quick question. I'm new to coffescript. How would we add placeholder text stating, "No new notifications" IF new getNewNotifications = 0, using the notifications.js.coffee file and the example code you provided for the navbar layout. I have been trying for a while with no luck...

Hey Dan! I'd change it to something like this: https://gist.github.com/exc...

Ahhh...Thank you so much for sharing! I'll keep sending students to your site.

I appreciate it! :)


Hey Chris Oliver thanks again for another awesome tutorial! If noticed a bug after implementing this. If a user does an action and then the user is destroyed later, this will raise a error when the receiver loads his notifications. For example, it will give an 'undefined method for nil:NilClass' when loading the notifications as the user no longer exist.

I guess the question is how more on polymorphic associations and how do I implement a dependent destroy for the notifications. I tried:

has_many :notifications, foreign_key: :receiver_id, dependent: :destroy
has_many :notifications, foreign_key: :actor_id, dependent: :destroy

but both won't work.

Is there a quick way to implement this or can I just do an after delete callback to remove all notifications?

Cheers!

Hey Ariff,

Since the notifications include two users (the receiver and the actor) you need to make sure that if a user gets destroyed, then it removes notifications on both sides. What you've written should work, except that you need to give one of the two has_many assocations a different name because the second one overrides the first one. I would rename the second to something like

has_many :sent_notifications, class_name: "Notification", foreign_key: :actor_id, dependent: :destroy

This will give you the association that can still get automatically deleted without overriding the original one. Plus we rename this one so that you can still use the common "current_user.notifications" to get the ones where you are the receiver.

Thanks @excid3:disqus! Works great!


Isn't it better to index the notifications to users table?? But as here user can be either actor or recipient making me confused..


I would love to see this integrated with React or, really, ActionCable Notifications + React. Great episode.

React stuff is coming soon! :)

Awesome!


How do you prevent the numbers from "flickering" every time the page refreshes?

Just render them in your navigation snippet so that they're already there when the page loads. It adds query time which slows down your page load, but won't make them appear later. The other option is to just style your CSS with that space already taken up so the view doesn't shift and cause your eye to look at it.


I wonder if this works like actioncable notification I have planted..because as I see you need to refresh the page in order to load the new notifications...

I believe Chris created a newer video that shows how to do this using actioncable.

Any ideas on solving this issue?


Is there another way than checking the db every few seconds? Sounds like it could be taxing. Also I implemented this in a web app I am working on that uses React on the front end (via react rails) and there seems to be a few second delay before the notification appears. I guess moving the logic from jQuery into React itself may help. I was just wondering if there are any other ways. Thank you.

I have noticed this same issue. The bell itself doesn't appear for about 2 seconds, and then 3 seconds later, the notification number appears... If anyone has a fix, that would be great.


I have followed the steps in the tutorial, however, when i check the rails console, no notification is not being created when i create a comment (forum_thread) on a post (forum_post).


Thanks for this course Chris. I'm trying to implement this to an app am building (I want to create the notifications for comments where the comment belongs to episode and episode belongs to story and genre)... When i checked out Notification.all in my console it outputted it but when i navigated to http://localhost:3000/notifications.json i got an error telling me that "undefined method `episode_path' for #<#<class:0x157f1538>:0x15149e68>"

Here is my index.json.jbuilder
https://uploads.disquscdn.c...


i'm having this error "undefined method `underscore' for nil:NilClass" , i can't quite figure it out , Error happen ,when rendering the json template

json.template render partial: "notifications/#{notification.notifiable_type.underscore.pluralize}/#{notification.action}", locals: {notification: notification}, formats: [:html]


I did find myself having issues with the jQuery map method in the handleSuccess using Rails 5.1 (with jQuery). Instead I found the Ruby map works just fine:

items = data.map (notification) ->
  "<li><a class='dropdown-item' href='#{notification.url}'>'#{notification.sender} #{notification.action} a #{notification.notifiable.type}'</a></li>"



Hey Chris, I was wondering how you would tackle the notification type in cases where the text you want to render isn't exactly the class name and there's more text that depends on the notifiable object. For example, let's say I want to have the following two notifications:

  • "John D started following you"
  • "Jane D sent you a friend request"

I did a quick test and added a `notification_to_s` method to my `Follow` and `FriendRequest` models like so:

# follow.rb
  def notification_to_s
    "following you"
  end

# friend_request.rb
  def notification_to_s
    "you a friend request"
  end

And then adapted the jbuilder method like this:

# index.json.jbuilder
# ...
  json.notifiable do
    json.type notification.notifiable.notification_to_s
  end

This doesn't seem as dynamic as your example. Can you think of a better way to do this?

Did you end up doing a react version of this? I am having a hard time integrating my redux module into the rails header.


Hi Chris!

I am trying to implement the notification feature and it works perfectly up to the point where I try to fetch the @notifications div in notifications.js.coffee file.

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

  setup: ->
    console.log(@notifications)

  jQuery ->
    new Notifications

I know that the file loads because if I put an alert message it executes on page load. But when I do the code above it dont get anything consoled..


Hi Chris!

The notifications are working. What you call threads, we call posts, and what you call posts, we call comments.

Two issues:

1) It only works when the json.url line is commented out:

json.url post_path(notification.notifiable.post, anchor: dom_id(notification.notifiable)) 

As soon I uncomment, notifications totally stop working--the number disappears from the bell, and the notification messages themselves also disappear. Once I comment out the line again, the bell numbers return, and so do the notifications. Thoughts on how to get that to work? We definitely would like each notification to be linkable to that particular event.

2) we are showing messages for both posts (post_path) and also comments (comment_path). But how will index.json.builder know when to follow the post_path, and when to follow the comment_path? And then again, once we add other notifiable events, like reaching a higher level, etc.?

Thanks very much!
-Monroe

If it works commented out, then you're probably throwing an error on that line. Read the logs to debug it. :)

Okay! I'll try that. :D

This is the error in the rails console:

https://gyazo.com/c14ed47cb5fbe8dbf3cb7158c4865407

Does this mean I forgot to create a post method somewhere?

No, it says you tried to call the "post" method on a Post object. It's not a Comment, it's a Post.


Hi Chris, I'm learning alot from this tutorial. I really appreciate the throughness that you have for this tutorial. I am however, facing an issue where I am unable to retrieve the jQuery from the index page. My console is unable to detect anything from the console.log.

Could you advise me what would be the possible scenario where I made a mistake?

Joseph, I had a similar issue, and solved it by adding a '//= require_tree' line at the application.js.


Having trouble implementing it with Bulma. Any ideas?


Hi,

this is working good for me. but in other localhost applications also calling /notifications.json.
And getting error ActionController::RoutingError (No route matches [GET] "/notifications.json").


It seems to be a problem when following the links on the notifications dropdpwn (actually following all the links in the app). *When following the links the notifications feature doesn't work anymore :( Only on refreshing the page! *
Any ideas on solving this issue?
Cheers


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.