如何在Rails 4中使用Public Activity gem来通知帖子评论帖子中涉及的每个用户?

时间:2016-08-06 03:04:40

标签: ruby-on-rails

我的应用包含有评论的帖子。这是我想要的功能:用户在他创建的帖子上看到评论活动,评论者看到他评论过的帖子的评论活动。

我的模特:

class Post < ActiveRecord::Base
belongs_to :user
belongs_to :course
has_many :comments, dependent: :destroy
end


class Comment < ActiveRecord::Base
include PublicActivity::Model
tracked except: :update, owner: ->(controller, model) { controller && controller.current_user }

belongs_to :post
belongs_to :user

end

活动控制器:

class ActivitiesController < ApplicationController
def index
@activities = PublicActivity::Activity.order("created_at desc")

end
end

活动索引视图:

<% @activities.each do |activity| %>
<div class="activity">
<%= link_to activity.owner.username, activity.owner if activity.owner %>

added comment to <%= link_to activity.trackable.post.title, activity.trackable.post %>
 </div>
 <% end %>

谢谢!

1 个答案:

答案 0 :(得分:1)

我担心PublicActivity gem不是为此而设计的。它意味着在一个活动发生时创建一个活动。在您的情况下,如果活动发生,您需要创建可能的许多通知记录(1 /用户)。我的工作遇到了同样的问题,我们决定创建一个类似于PublicActivity实现的Notification模型。

class User < ActiveRecord::Base
  has_many :notifications, foreign_key: :notified_user_id, dependent: :destroy
end

class Comment < ActiveRecord::Base
  # maybe it would be better to name it as inverse_notifications
  has_many :notifications, as: :trackable, dependent: :destroy
end

class Notification < ActiveRecord::Base
  belongs_to :trackable, polymorphic: true
  belongs_to :acting_user, class_name: "User"
  belongs_to :notified_user, class_name: "User"

  validates_presence_of :trackable, :notified_user, :key

  scope :unread, -> { where("read_at IS NULL") }
end

这允许您在创建注释时创建两种类型的通知:

  • 拥有key: "post.commented"
  • 的所有者之一 对于key: "comment.created" 的评论者,
  • 很多

如果用户已经看到它,则可以设置read_at属性,因此您可以在前端添加不同的样式。