【发布时间】:2015-12-19 20:32:14
【问题描述】:
如果我对您的状态发表评论,然后您回复评论,我不会收到通知让我知道您发表了评论。
目前只有状态的所有者会收到通知。我们怎样才能让任何评论状态的人也收到通知?
模型
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 %>
【问题讨论】:
-
你的问题太笼统了。 “每当用户对某个状态发表评论时,对该状态发表的任何评论应通知您已发表其他评论”。你需要了解什么?您是在问如何知道何时 通知,还是在问如何 通知用户? 通知到底是什么意思?模型中的某些值发生了变化,发送的电子邮件,弹出窗口......
-
如果我评论你的价值。然后,如果您对该值发表评论。我没有收到通知让我知道您发表了评论。只有其值的人才能收到通知。也许
def create_notification中有一种方法可以使这项工作@brito -
@AnthonyGalli.com 是的,因为通知总是使用
user: author,和author = valuation.user创建的(这在create_notification内)。因此,您需要创建传递Comment的作者而不是Valuation的作者的特定通知。 -
抱歉,@brito 没用。例如,cmets 是在用户 1 拥有的评估 1 上进行的。当用户 2 在评估 1 上进行 cmets 时,rails 是如何假设用户 1 对评估 1 的评论应该通知用户 2 的?用户 2 不拥有估价 1。对估价做出评论,即使是那些作为对早期 cmets 的回复的评论。也许在代码中有一种说法,“就评论/通知而言,估值 1 也属于用户 2”?
-
"rails 是如何知道用户 1 对估价 1 的评论应该通知用户 2 的?"估值 1 包含来自用户 1 和用户 2 的 cmets,对吗?然后,估值 1 可以识别用户 1 和 2。所以你只需要遍历每个估值的 cmets,存储唯一用户(因为用户可能已经评论了不止一次,我们只希望每个用户有 1 个通知)然后通知他们。
标签: ruby-on-rails ruby notifications