27

Basically, I want to create a notification like Facebook and Stackoverflow. Specifically, in a Post-Comments system, when a post get commented, everyone involved (people who creates the post and who create comments, except the new commenter) gets a notification message that this post get commented. And the notification get dismissed when people have read it.

I have tried to use mailboxer gem to implement it, but saddly there is no example available using its related methods, including social_stream itself.

Is there other way to create the Notification System?

And when I try to create it from scratch I get several problems:

    Model Notification
    topic_id: integer
    user_id: integer
    checked: boolean #so we can tell whether the notification is read or not
  1. Dismissing the notication after being read by users

I think we just need to turn every notification messages' "checked" attribute to true after user visit the index of notification.(In the NotificationsController)

    def index
      @notifications=current_user.notication.all
      @notification.each do |notification|
         notification.checked = true
      end
      @notification.save!
    end

2.Selecting users to notify(and exclude the user making new comment)

I just have no idea in wrting queries....

3.Creating notifications

I think this should be something like

    #in CommentController
    def create
      #after creating comments, creat notifications
      @users.each do |user|
        Notification.create(topic_id:@topic, user_id: user.id)
      end
    end

But I think this is really ugly

There is no need to anwer the 3 problems above, Any simple solution to the Notification System is preferable , thanks....

4

2 回答 2

13

我认为你走在正确的道路上。

稍微好一点的通知#index

def index
  @notifications = current_user.notications
  @notifications.update_all checked: true
end
  1. 通知此用户

    User.uniq.joins(:comments).where(comments: {id: @comment.post.comment_ids}).reject {|user| user == current_user }
    

参与@comment 发表评论的唯一用户,拒绝(从结果中删除)current_user。

  1. 正如 João Daniel 指出的观察者,它比 after_create 更受欢迎。这个“Rails 最佳实践”很好地描述了它:http ://rails-bestpractices.com/posts/2010/07/24/use-observer
于 2013-03-13T14:16:47.613 回答
9

有一个名为公共活动的神奇宝石,您可以根据需要对其进行自定义,这是 railscast http://railscasts.com/episodes/406-public-activity中有关它的截屏视频, 希望对您有所帮助。

更新

在我的 Rails 应用程序中,我制作了一个类似的通知系统,用于向所有用户发送通知,但在索引操作中,您可以使用

current_user.notifications.update_all(:checked=>true)

并且还可以只向用户发送一个通知,而不是多次有人对帖子发表评论,您可以使用 unique_by 方法

  @comments =@commentable.comments.uniq_by {|a| a[:user_id]}

然后您可以仅向以前评论的用户发送通知

 @comments.each do |comment|
 comment.user.notifications.create!(....
 end 

希望对你有帮助

于 2013-03-13T15:29:09.077 回答