ActiveRecord - 按所包含的表的属性分组

时间:2015-08-28 17:49:02

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

我有以下两个模型

post_comment.rb

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

reply.rb

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

我有以下查询获取所有post_comments并包含各自的回复:

PostComment.all.includes(:回复)

但是,我还希望将回复模型的reply_id属性的回复分组

理想情况下,我最终会直接从数据库中得到以下内容:

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

谢谢!

2 个答案:

答案 0 :(得分:0)

我认为ActiveRecord无法做到这一点

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

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

您可以将虚拟列添加到模型

答案 1 :(得分:0)

要按回复模型的reply_id属性对回复进行分组,您可以执行以下操作:

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