如何在rails中创建通知系统?

cqc*_*991 27 gem notifications ruby-on-rails

基本上,我想创建一个像Facebook和Stackoverflow的通知.具体来说,在帖子评论系统中,当帖子得到评论时,所涉及的每个人(创建帖子的人和创建评论的人,除了新的评论者)都会收到一条通知消息,说明此帖子已被评论.当人们阅读通知时,通知就会被驳回.

我曾尝试使用mailboxer gem来实现它,但遗憾的是没有使用其相关方法的可用示例,包括social_stream本身.

还有其他方法来创建通知系统吗?

当我尝试从头开始创建它时,我遇到了几个问题:

    Model Notification
    topic_id: integer
    user_id: integer
    checked: boolean #so we can tell whether the notification is read or not
Run Code Online (Sandbox Code Playgroud)
  1. 用户阅读后删除通知

我认为我们只需要在用户访问通知索引后将每个通知消息的"已检查"属性设置为true.(在NotificationsController中)

    def index
      @notifications=current_user.notication.all
      @notification.each do |notification|
         notification.checked = true
      end
      @notification.save!
    end
Run Code Online (Sandbox Code Playgroud)

2.选择要通知的用户(并排除用户发表新评论)

我只是不知道如何查询......

3.创建通知

我认为这应该是这样的

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

但我认为这真的很难看

没有必要解决上面的3个问题,任何简单的通知系统解决方案都是可取的,谢谢......

Leo*_*lán 13

我认为你走的是正确的道路.

一个稍微好一点的通知#index

def index
  @notifications = current_user.notications
  @notifications.update_all checked: true
end
Run Code Online (Sandbox Code Playgroud)
  1. 通知此用户

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

参与@ comment的帖子评论的唯一用户拒绝(从结果中删除)current_user.

  1. 如JoãoDaniel所指出的观察者,它优于after_create.这个"Rails最佳实践"很好地描述了它:http://rails-bestpractices.com/posts/2010/07/24/use-observer


Rem*_*min 9

有一个叫做公共活动的惊人宝石,你可以根据需要自定义它,这里有一个关于它的视频直播http://railscasts.com/episodes/406-public-activity 希望可以帮到你.

更新

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

current_user.notifications.update_all(:checked=>true)
Run Code Online (Sandbox Code Playgroud)

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

  @comments =@commentable.comments.uniq_by {|a| a[:user_id]}
Run Code Online (Sandbox Code Playgroud)

然后,您只能向之前评论的用户发送通知

 @comments.each do |comment|
 comment.user.notifications.create!(....
 end 
Run Code Online (Sandbox Code Playgroud)

希望能帮助你

  • 我已经看过这一集,但我认为这是针对状态Feed,不适合通知系统? (2认同)