The first step is to create a new model and controller for notification
$ rails g model Notification post:references comment:references user:references read:boolean $ rake db:migrate $ rails g controller Notifications index
Once this is done, the next step is to add has_many: notifications in the User, Post, and Comment models.
Once this is done, add the following code to the comment model:
after_create :create_notification private def create_notification @post = Post.find_by(self.post_id) @user = User.find_by(@post.user_id).id Notification.create( post_id: self.post_id, user_id: @user, comment_id: self, read: false ) end
The above snippet creates a notification after creating a comment. The next step is to edit the notification controller so that the notification can be deleted and the user can mark the notification as read:
def index @notifications = current_user.notications @notifications.each do |notification| notification.update_attribute(:checked, true) end end def destroy @notification = Notification.find(params[:id]) @notification.destroy redirect_to :back end
The next thing to do is a way to delete a notification when deleting a comment:
def destroy @comment = Comment.find(params[:id]) @notification = Notification.where(:comment_id => @comment.id) if @notification.nil? @notification.destroy end @comment.destroy redirect_to :back end
The last thing to do is to create several views. You can do whatever you want
source share