如果我对您的状态发表评论,然后您发表评论,我就不会收到通知,让我知道您的评论。
目前只有状态的所有者才会收到通知。我们如何才能获得对状态发表评论的人也应该得到通知呢?
模型
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 %>
答案 0 :(得分:4)
您必须检索已对评估进行评论的用户列表,而不是为作者创建一个通知。我在评论模型中看不到belongs_to :user
,但我会假设有一个,因为您可以在current_user.comments
中执行CommentsController
。
让我们在has_many
中添加Valuation
关系来检索给定估值的所有评论员:
class Valuation < ActiveRecord::Base
belongs_to :user
has_many :notifications
has_many :comments
has_many :commentators, -> { distinct }, through: :comments, source: :user
end
如果您使用的是Rails版本&lt; 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