【问题标题】:How to implement a notification system?如何实施通知系统?
【发布时间】:2013-10-01 08:53:26
【问题描述】:

我已经创建了一个帖子和 cmets 系统,现在我将添加一个通知系统,以在每次有人发表评论时提醒对话中的每个用户。

我的问题是,就构建该系统的数据库而言,哪种方式最好? 我想到了一个包含以下字段的通知表:

id_notification | sent_by | id_user_receiver | id_post
      1              2             3              10

在此示例中,ID 为 2 的用户对 ID 为 10 的帖子发表了评论,而 ID 为 3 的用户收到了通知。但是,如果对话涉及 100 或 1000 个用户,则每次某个用户在对话上写入时,我都会在数据库中结束 100 或 1000 条记录。我认为不是正确的方法。有什么更好的解决方案?

【问题讨论】:

    标签: mysql notifications


    【解决方案1】:

    我认为这是正确的方法,如果用户阅读了通知,您可以简单地删除该行,因为将来不再需要。除此之外,1000 条记录也不算什么。您可以轻松地在表中拥有数百万条记录,只需确保索引正确即可。

    【讨论】:

      【解决方案2】:

      第一步是为通知创建一个新模型和控制器

         $ rails g model Notification  post:references comment:references user:references read:boolean
      
         $ rake db:migrate
         $ rails g controller Notifications index
      

      完成后,下一步是将 has_many :notifications 添加到 User、Post 和 Comment 模型中。

      完成后,将以下代码添加到 Comments 模型中:

             after_create :create_notification
      
             private
      
               def create_notification
                 @post = Post.find_by(self.post_id)
                 @user = User.find_by(@post.user_id).id
                   Notification.create(
                   post_id: self.post_id,
                  user_id: @user,
                   comment_id: self,
                   read: false
                    )
              end
      

      上面的 sn-p 在创建评论后创建通知。 下一步是编辑 Notifications 控制器,以便可以删除通知并且用户可以将通知标记为已读:

             def index
               @notifications = current_user.notications
               @notifications.each do |notification|
               notification.update_attribute(:checked, true)
            end
           end
      
            def destroy
              @notification = Notification.find(params[:id])
              @notification.destroy
              redirect_to :back
            end
      

      接下来要做的是设置一种在删除评论时删除通知的方法:

                def destroy
                 @comment = Comment.find(params[:id])
                 @notification = Notification.where(:comment_id => @comment.id)
                   if @notification.nil?
                     @notification.destroy
                   end
                 @comment.destroy
                 redirect_to :back
              end
      

      最后要做的是创建一些视图。你可以做任何你想做的事

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-12
        • 2013-02-21
        • 1970-01-01
        • 2018-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-19
        相关资源
        最近更新 更多