【问题标题】:Comment notification to users in rails?向 Rails 中的用户发送评论通知?
【发布时间】:2010-11-06 07:06:15
【问题描述】:

我的 webapp 有注册用户,它也有文章、博客文章、八卦。 对于所有这些资源,我有一个多态评论模型,如下所示。

id  content         commentable_id  commentable_type   user_id  created_at  updated_at
1   Frist comment   2               Article            1        ....
2   Second comment  3               Post               2        .....

因此,对于每个可评论资源,我在可评论资源底部都有一个评论表单供用户评论。 我想要一个复选框,在提交评论时选中时,用户应该会收到通知,无论是在收件箱还是电子邮件中,因为我们已经在用户注册时拥有它,稍后会添加其他新的 cmets。

我想要一些模型,例如 Notifications,我可以在其中存储 commentable_type、commentable_id 和 user_id(如果使用匹配的可评论和用户创建了任何新评论,应将通知发送给谁?

如何实现 Comment 和 Notification 之间的关联?对于检查部分,如果有任何人订阅特定的可评论资源,则使用 after_create 钩子创建一个 CommentObserver 来初始化搜索并在有任何匹配记录时发送通知。

但我很困惑实现这一点的关联、模型、控制器和视图会是什么样子?既然评论模型已经是多态的了,我可以将通知模型也创建为多态吗??

【问题讨论】:

    标签: ruby-on-rails ruby comments notifications


    【解决方案1】:

    您无需插件即可轻松完成此操作。 创建一个数据库表来存储用户对帖子的通知订阅。然后,每次创建评论时,查询数据库并使用ActionMailer 向所有用户的地址发送电子邮件。

    【讨论】:

      【解决方案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
      

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

      【讨论】:

        猜你喜欢
        • 2020-03-29
        • 2019-08-26
        • 1970-01-01
        • 2015-11-30
        • 1970-01-01
        • 1970-01-01
        • 2012-02-02
        • 1970-01-01
        • 2013-06-04
        相关资源
        最近更新 更多