如何通知评论者?

How to notify the commenter?

如果我对你的状态发表评论然后你回复我,我不会收到通知让我知道你发表了评论。

目前只有状态的所有者会收到通知。我们如何才能让任何对状态发表评论的人也收到通知?

型号

class Comment < ActiveRecord::Base
  after_save :create_notification
  has_many :notifications
  def create_notification
    author = valuation.user
    notifications.create(
      comment:      self,
      valuation:    valuation,
      user:         author,      
      read:         false
    )
  end
end

class Notification < ActiveRecord::Base
  belongs_to :comment
  belongs_to :valuation
  belongs_to :user
end

class Valuation < ActiveRecord::Base
  belongs_to :user
  has_many :notifications
  has_many :comments
end

控制器

class CommentsController < ApplicationController
  before_action :set_commentable, only: [:index, :new, :create]
  before_action :set_comment, only: [:edit, :update, :destroy]

  def create
    @comment = @commentable.comments.new(comment_params)
    if @comment.save
      redirect_to @commentable, notice: "Comment created."
    else
      render :new
    end
  end

  private

  def set_commentable
    @commentable = find_commentable
  end

  def set_comment
    @comment = current_user.comments.find(params[:id])
  end

  def find_commentable
    if params[:goal_id]
      Goal.find(params[:goal_id])
    elsif params[:habit_id]
      Habit.find(params[:habit_id])
    elsif params[:valuation_id]
      Valuation.find(params[:valuation_id])
    elsif params[:stat_id]
      Stat.find(params[:stat_id])
    end
  end
end

class NotificationsController < ApplicationController
  def index
    @notifications = current_user.notifications
    @notifications.each do |notification|
      notification.update_attribute(:read, true) 
    end
  end
end

观看次数

#notifications/_notification.html.erb
commented on <%= link_to "your value", notification_valuation_path(notification, notification.valuation_id) %>

#comments/_form.html.erb
<%= form_for [@commentable, @comment] do |f| %>
  <%= f.text_area :content %>
<% end %>

您不必为作者创建一个通知,而是必须检索对估值发表评论的用户列表。我在 Comment 模型中没有看到 belongs_to :user,但我假设有一个,因为您可以在 CommentsController.

中执行 current_user.comments

让我们在 Valuation 中添加一个 has_many 关系来检索给定估值的所有评论员:

class Valuation < ActiveRecord::Base
  belongs_to :user
  has_many :notifications
  has_many :comments
  has_many :commentators, -> { distinct }, through: :comments, source: :user
end

如果您使用的 Rails < 4 版本,您应该将 -> { distinct } 替换为 uniq: true

然后,您可以简单地使用这个新关系为 Comment 模型中的所有评论员创建通知:

class Comment < ActiveRecord::Base
  after_save :create_notification
  belongs_to :user
  belongs_to :valuation
  has_many :notifications

  def create_notification
    to_notify = [valuation.user] + valuation.commentators
    to_notify = to_notify.uniq
    to_notify.delete(user)  # Do not send notification to current user
    to_notify.each do |notification_user|
      notifications.create(
        comment:      self,
        valuation:    valuation,
        user:         notification_user,      
        read:         false
      )
    end
  end
end