Rails 多个 group_by 到阵列

Rails multiple group_by to array

这是我要排序的模型类型。

我有一个User,他可以有多个Post,每个人都有很多Statistic

总而言之,这就是我所拥有的:

class User < ActiveRecord::Base
  has_many :posts
  has_many :statistics
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :statistics
end

class Statistic < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
end

最后我想要的是两个tables(一个单元格=一天):

  1. 一个 table 可以获取按天分组的用户的所有统计信息,我已经成功获取了它
  2. 第二个有点复杂。我想要同样的东西,但按 Post ID
  3. 分组

对于第一个,我使用了:

# Group by day all statistics from one user
stats_by_date = current_user.statistics.group_by { |s| s.created_at.to_date }
# Transform the hash into an Array (one cell = one day)
@overall_statistics = stats_by_date.values

对于第二个,我成功地将结果分组为 Post ID 和天数,但我不知道如何将其转换为 exploitable 数组,这意味着一个 table 每个 Post ID 和每个 table 一个单元格一天:

# Group statistics by posts
stats_by_post = current_user.statistics.group_by { |s| [s.created_at.to_date, s.post_id] }

这是我得到的哈希值:

{
#[Thu, 07 May 2015, 2]=>[#<Statistic id: 68>, #<Statistic id: 69>, #<Statistic id: 74>],
#[Thu, 08 May 2015, 1]=>[#<Statistic id: 70>, #<Statistic id: 71>, #<Statistic id: 72>, #<Statistic id: 73>, #<Statistic id: 80>],
#[Thu, 08 May 2015, 2]=>[#<Statistic id: 70>, #<Statistic id: 71>, #<Statistic id: 72>, #<Statistic id: 73>, #<Statistic id: 80>],
# ...
}

如何为每个 post 创建一个 table?

我要的是这个:

#--Table for : Post ID 2
#----First Cell (Thu, 07 May 2015)
#------[#<Statistic id: 68>, #<Statistic id: 69>, #<Statistic id: 74>]
#----Second cell (Thu, 08 May 2015)
#------[#<Statistic id: 70>, #<Statistic id: 71>, #<Statistic id: 72>, #<Statistic id: 73>, #<Statistic id: 80>]

#--Table for : Post ID 1
#----First Cell (Thu, 07 May 2015)
#------[#<Statistic id: 70>, #<Statistic id: 71>, #<Statistic id: 72>, #<Statistic id: 73>, #<Statistic id: 80>]

我可以看到两种构建嵌套哈希的方法,正如您所描述的那样:

1) 迭代两次,在两个层次上使用group_by

statistics_by_post = current_user.statistics.group_by(&:post_id)
@statistics_by_day_by_post = statistics_by_post.map do |p_id, stats|
  [p_id, stats.group_by{ |s| s.created_at.to_date }]
end.to_h

2) 迭代一次,手动分组:

@statistics_by_day_by_post = {}
current_user.statistics.each do |s|
  post_id, day = s.post_id, s.created_at.to_date
  @statistics_by_day_by_post[post_id] ||= {}
  @statistics_by_day_by_post[post_id][day] ||= []
  @statistics_by_day_by_post[post_id][day] << s
end

HTH!