有多种方法可以实现这一点。这实际上取决于您想要涵盖哪种类型的通知以及您需要收集有关通知的哪些信息以将其显示给正确的用户。如果您正在寻找一个简单的设计,仅涵盖有关已发布评论的通知,您可以使用以下组合多态关联 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
将是“喜欢”的事物的所有者。您甚至可能需要通知多个人,例如当有人评论照片时通知照片中标记的所有人员。
希望这可以帮助。