【问题标题】:ActiveRecord - Group by attribute of included tableActiveRecord - 按包含表的属性分组
【发布时间】:2015-08-28 17:49:01
【问题描述】:

我有以下两种型号

post_comment.rb

class PostComment < ActiveRecord::Base
  has_many :replies, dependent: :destroy
  ...
end

回复.rb

class Reply < ActiveRecord::Base
  belongs_to :post_comments
  belongs_to :reply
  ...
end

我有以下查询,它获取所有 post_cmets 并包含它们各自的回复:

PostComment.all.includes(:replies)

不过,我还想通过回复模型的 reply_id 属性对 的回复进行分组

理想情况下,我希望直接从 DB 中得到类似以下内容:

[
  <Post 1:
    replies: { nil: [...], 1: [...], 2: [...], ... }
    ...
  >,
  <Post 2:
    replies: { nil: [...], 123: [...], 341: [...], ... }
    ...
  >,
]

谢谢!

【问题讨论】:

    标签: sql ruby-on-rails-4 activerecord


    【解决方案1】:

    我不认为 ActiveRecord 可以做到这一点

    我们可以这样分组依赖,但也许不是你想要的方式

    posts = PostComment.all.includes(:replies)
    for post in posts
      ...
     replies_map = post.replies.group_by(&:reply_id)
      ...
    end
    

    你可以为模型添加一个虚拟列

    【讨论】:

      【解决方案2】:

      要按回复模型的reply_id 属性对回复进行分组,您可以这样做:

      PostComment.joins(:replies).group('replies.reply_id')
      

      【讨论】:

      • 得到以下输出:PG::UndefinedTable: ERROR: missing FROM-clause entry for table "replies"
      • @delisdeli 请再试一次我更新的答案。它现在应该可以工作了。
      • 我不认为这会返回我正在寻找的格式
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2022-01-06
      • 2020-05-07
      • 2015-03-11
      • 2022-01-25
      • 1970-01-01
      相关资源
      最近更新 更多