我目前正在使用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)
如果我正确地解释你,你是否正在努力有效地获得一系列不属于特定帖子的PostComments?
如果是这种情况,只需使用not
方法:
x = # given Post id
post = Post.find(x).id
postcomments = PostComment.where.not(post_id: post)