mysql - 如何向 Rails 中的多态评论的所有评论者发送通知?
问题描述
我正在使用多态关联进行评论。我想向所有评论帖子的用户发送通知。
- 假设user1发布了一个帖子。
- User2对此发表评论。
- 用户 1 收到通知 (users = User.joins (:posts).where(:posts => {id: params[:post_id]})) “用户 2 发表了评论”
- 再次,User1评论。
- 现在,User2应该收到通知(users= ??????)
- 如果user2、user3、user4发表评论,则所有相关用户都应该收到通知。
评论.rb
class Comment < ApplicationRecord
belongs_to :user
belongs_to :commentable, polymorphic: true
has_many :comments, as: :commentable
validates :comment, presence: true
after_create :notifications
def notifications
#Create Notification
users = ????
(users-[@current_user]).each do |user|
Resque.enqueue(NotifyJob, Notification.create(
recipient: user,
actor: @current_user,
action: "posted",
notifiable: @comment))
end
end
end
用户.rb
class User < ApplicationRecord
has_many :posts, dependent: :destroy
has_many :comments, as: :commentable, dependent: :destroy
has_many :notifications, foreign_key: :recipient_id, dependent: :destroy
end
post.rb
class Post < ApplicationRecord
belongs_to :user
validates :comment, presence: true
validates :user_id, presence: true
has_many :comments, as: :commentable
end
评论控制器.rb
module Api
module V1
class CommentsController < ApplicationController
skip_before_action :verify_authenticity_token
before_action :authorize_request
before_action :find_commentable
def new
@comment = Comment.new
end
def create
@comment = @commentable.comments.new(comment_params)
@comment.user = @current_user
if @comment.save
render json: @comment, status: :created
else
render json: { errors: @comment.errors.full_messages },
status: :unprocessable_entity
end
end
def show
@comment = Comment.find(params[:id])
if !@comment.nil?
render json: @comment, status: :ok
else
render json: {errors: @comment.errors.full_messages}, status: :unprocessable_entity
end
end
private
def comment_params
params.permit(:comment)
end
def find_commentable
@commentable = Comment.find_by_id(params[:comment_id]) if params[:comment_id]
@commentable = Post.find_by_id(params[:post_id]) if params[:post_id]
end
end
end
end
解决方案
我没有做太多改变。我刚刚做了这样的改变:
评论.rb
class Comment < ApplicationRecord
belongs_to :user
belongs_to :commentable, polymorphic: true
has_many :comments, as: :commentable
validates :comment, presence: true
private
after_commit :create_notifications, on: [:create]
#Create Notification
def create_notifications
commentable = self.commentable
commentors= Comment.where(commentable: commentable).pluck(:user_id)
users = User.find(commentors)-[self.user]
users.each do |user|
Resque.enqueue(NotifyJob, Notification.create(
actor: self.user,
recipient: user,
action: "posted",
notifiable: self.commentable))
end
end
end
推荐阅读
- android - android:如何在对话框全屏上隐藏底部按钮
- android-studio - 反转抽屉内的列表视图
- kubernetes - 如何通过 API 推出重启部署?
- vba - 检查插入点是在 selection.range 的开头还是结尾
- python-3.x - python3和pypy3有什么区别
- java - 如何在数据库重新启动/断开连接时自动重新连接数据库,该数据库在 openshift 中部署为 java jar 应用程序?
- ios - 如何为 iOS 应用集成 eSewa 支付网关?
- php - POST 路线中可选 slug 的可选训练斜线
- c# - LINQ:记录列表多于预期记录
- javascript - 如何在Javascript中一次性过滤进出数组元素