Facebook 的通知(数据库实现)

2023-12-11

我想知道 Facebook 如何实现他们的通知系统,因为我想做类似的事情。

  • FooBar 评论了你的状态
  • Red1、Green2 和 Blue3 对您的照片发表了评论
  • MegaMan 和其他 5 人评论了您的活动

我无法将多个通知写入单个记录,因为最终我将拥有与每个通知关联的操作。另外,在视图中,当单个主题存在一定数量的通知时,我希望将通知呈现为可扩展列表。

  • FooBar 评论了您的状态(操作)
  • Red1、Green2 和 Pink5 对您的照片发表了评论 [+]
  • MegaMan and 3 others commented on your event [-]
    • MegaMan 评论了您的活动(操作)
    • ProtoMan 评论了您的活动(操作)
    • 巴斯评论了您的活动(行动)
    • DrWilly 对您的活动发表了评论(行动)

Cheers!

PS顺便说一句,我正在使用 postgres 和 Rails。


有多种方法可以实现这一点。这实际上取决于您想要涵盖哪种类型的通知以及您需要收集有关通知的哪些信息以将其显示给正确的用户。如果您正在寻找一个简单的设计,仅涵盖有关已发布评论的通知,您可以使用以下组合多态关联 and 观察者回调:

class Photo < ActiveRecord::Base
# or Status or Event
    has_many :comments, :as => :commentable
end

class Comment < ActiveRecord::Base
    belongs_to :commenter
    belongs_to :commentable, :polymorphic => true # the photo, status or event
end

class CommentNotification < ActiveRecord::Base
    belongs_to :comment
    belongs_to :target_user
end

class CommentObserver < ActiveRecord::Observer
    observe :comment

    def after_create(comment)
        ...
        CommentNotification.create!(comment_id: comment.id,
          target_user_id: comment.commentable.owner.id)
        ...
    end
end

这里发生的情况是,每张照片、状态、事件等都有很多评论。 AComment显然属于:commenter但也为了一个:commentable,它可以是照片、状态、事件或您希望允许评论的任何其他模型。然后你就有了一个CommentObserver这会观察你的Comment模型并在发生任何事情时执行某些操作Comment桌子。在这种情况下,经过一段Comment创建后,观察者将创建一个CommentNotification包含评论的 id 和拥有该评论相关内容的用户的 id (comment.commentable.owner.id)。这需要您实现一个简单的方法:owner对于您想要发表评论的每个模型。因此,例如,如果可评论是照片,则所有者将是发布该照片的用户。

这个基本设计应该足以帮助您入门,但请注意,如果您想为评论之外的其他内容创建通知,您可以通过在更通用的环境中使用多态关联来扩展此设计。Notification model.

class Notification < ActiveRecord::Base
    belongs_to :notifiable, :polymorphic => true
    belongs_to :target_user
end

通过这种设计,您将“观察”您的所有notifiables(您想要为其创建通知的模型)并在您的after_create打回来:

class GenericObserver < ActiveRecord::Observer
    observe :comment, :like, :wall_post

    def after_create(notifiable)
        ...
        Notification.create!(notifiable_id: notifiable.id, 
                           notifiable_type: notifiable.class.name,
                            target_user_id: notifiable.user_to_notify.id)
        ...
    end
end

这里唯一棘手的部分是user_to_notify方法。所有型号notifiable必须根据模型的不同以某种方式实现它。例如,wall_post.user_to_notify只是墙的所有者,或者like.user_to_notify将是“喜欢”的事物的所有者。您甚至可能需要通知多个人,例如当有人评论照片时通知照片中标记的所有人员。

希望这可以帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Facebook 的通知(数据库实现) 的相关文章

随机推荐