ruby-on-rails - 获取用户评论和在同一查询中分组的所有评论

标签 ruby-on-rails postgresql ruby-on-rails-5

我目前正在使用 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/

相关文章:

java - 当 NULL LocalDate 作为输入给出时, native 命名查询失败并出现异常 "column is of type date but expression is of type bytea"

ruby-on-rails - Ruby on Rails 和 Redis:未初始化的常量 Redis::Namespace

ruby-on-rails - Rails find_or_create_by 创建重复项

ruby-on-rails - 多个 ActiveRecord 实例是否自动保持同步?

ruby-on-rails - 确定字符串是否为有效的浮点值

ruby-on-rails - RSpec:receive_message_chain的匹配参数

sql - PostgreSQL 创建类型 PL/pgSQL 和 cstring

python - 如何使用django向表中插入数据

ruby-on-rails - 如何更新 Rails Controller 以在 Model.create 错误时返回错误?

ruby-on-rails - 名称错误 : uninitialized constant on Heroku