gpt4 book ai didi

ruby-on-rails - 如何通知评论者?

转载 作者:数据小太阳 更新时间:2023-10-29 07:16:47 28 4
gpt4 key购买 nike

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

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

模型

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

Controller

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,但我假设有一个,因为您可以在 中执行 current_user.comments >评论 Controller

让我们在 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

关于ruby-on-rails - 如何通知评论者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32724064/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com