我目前正在使用 Rails 5 和 Postgresql。有一个模型 Post 可以有很多评论,通过一个叫做 PostComments 的模型,这样一个评论可以属于一个帖子,但是那个帖子可以有很多评论。我正在尝试获取所有评论,将属于特定用户的评论分组,而所有其他评论则不属于。
class Post < ApplicationRecord
has_many :post_comments
has_many :comments, through: :post_comments
...
class Coment < ApplicationRecord
has_many :post_comments
has_many :posts, through: :post_comments
...
目前我正在做两个查询和比较,比如:
foo = Comment.select(:id, :description)
bar = Comment.joins(:post).select(:id, :description).where(posts: { id: post_id })
remaining_comments = [foo - bar, foo]
这为我提供了特定商店的所有评论,以及所有剩余的评论,但我想知道是否有更好的方法来做到这一点?
最佳答案
您可以在一个查询中获取评论,如下所示:
@comments = Comment.left_outer_joins(:post)
.select("comments.id,comments.description,posts.id as post_id")
.where("posts.id = ? OR posts.id IS NULL", post_id })
然后使用group_by
拆分:
remaining_comments = @comments.group_by(&:post_id)
关于ruby-on-rails - 获取用户评论和在同一查询中分组的所有评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50145900/