rails-engine / notifications

🛎 Notifications Center engine like GitHub or other application for any Rails applications.
MIT License
389 stars 42 forks source link

How do I create notifications for comment replies? #27

Closed ghost closed 5 years ago

ghost commented 5 years ago

Hi! I've threaded commentable comment system on my app. I've been able to create notifications for a new comment. However, whenever a reply is added to a comment, the self.post.user for example gets the notification as a new comment. So my question is how do I create notification for replies too in such a way that when a reply is posted on a comment, the owner of the comment and the self.post.user should get notified of a reply and now as new comment?

comment.rb

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
  belongs_to :user
  belongs_to :parent, class_name: 'Comment', optional: true
  has_many :replies, class_name: 'Comment', foreign_key: :parent_id, dependent: :destroy

  validates :content, presence: true, length: { maximum: 255 }

  after_commit :notify_comment_created, on: [:create]
  def notify_comment_created
    return if self.commentable.blank?
    receiver_id = self.commentable&.user_id
    return if receiver_id.blank?
    # notified_user_ids = self.mentioned_user_ids || []
    # return if notified_user_ids.include?(receiver_id)

    Notification.create(
      notify_type: "comment",
      target: self,
      second_target: self.commentable,
      actor_id: self.user_id,
      user_id: receiver_id
    )
  end
end