1

我的 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        .....

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

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

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

但我很困惑关联、模型、控制器和视图会是什么样子来完成这个?由于评论模型已经是多态的,我可以将通知模型创建为多态吗?

4

2 回答 2

6

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

于 2009-06-26T22:29:51.020 回答
1

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

   $ 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

上面的代码片段会在创建评论后创建通知。下一步是编辑 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

最后要做的是创建一些视图。你想做什么,就可以做什么

于 2014-12-16T10:38:45.417 回答