首页 文章

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

提问于
浏览
27

基本上,我想创建一个像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
  • 用户读取后取消通知

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

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

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

但我认为这真的很难看

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

2 回答

  • 13

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

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

    def index
      @notifications = current_user.notications
      @notifications.update_all checked: true
    end
    
    • 通知此用户
    User.uniq.joins(:comments).where(comments: {id: @comment.post.comment_ids}).reject {|user| user == current_user }
    

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

  • 9

    有一个叫做公共活动的神奇宝石,你可以根据自己的需要自定义它,这里有一个关于它的截屏报道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
    

    希望能帮助你

相关问题