2016-08-06 78 views
0

我的應用程序有帖子,有評論。這是我想要的功能:用戶在他創建的帖子上看到評論活動,並且評論者在他評論的帖子上看到評論活動。如何使用Rails 4中的Public Activity gem來通知涉及帖子評論帖子的每個用戶?

我的模型:

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

恐怕PublicActivity gem沒有設計成這樣做。這意味着在一項活動發生時創建一項活動。在你的情況下,如果活動發生,你需要創建可能的許多通知記錄(1 /用戶)。在我的工作中,我們遇到了同樣的問題,因此我們決定創建一個類似於PublicActivity實現的通知模型。

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 

這允許你創建2種通知類型創建註釋時:

  • 一個爲業主與key: "post.commented"
  • 很多的評論者與key: "comment.created"

而且如果用戶已經看到它,可以設置read_at屬性,因此您可以在前端爲它們添加不同的樣式。

相關問題