按日期循环变量分组

时间:2016-10-06 05:58:12

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

我有一些运动成绩,我想在表格中循环并分组。例如;

|Sat, 20|
|Game 1 Results|
|Game 2 Results|
|Sun, 21|
|Game 3 Results|
|Sat, 27|
|Game 4 Results|

我的控制器

@matches = Match.group([:matchId, 'DATE(matchDate)']).inject([]) do |results, matches|
           team_names = Match.where(matchId: matches.matchId)
           results << [matches.id, matches.matchDate, team_names.first.team.name, team_names.last.team.name, team_names.first.points, team_names.last.points]
end

目前我正在进行基本循环,正在显示。

|Sat, 20|
|Game 1 Results|
|Sat, 20|
|Game 2 Results|
|Sun, 21|
|Game 3 Results|
|Sat, 27|
|Game 4 Results|

2 个答案:

答案 0 :(得分:2)

SQL GROUP BY用于聚合值:您可以获取每个日期的匹配数或目标总和,依此类推。 (Read more here.)但是如果你想要一组所有游戏的列表,那就不合适了。

您之前两次看到相同的日期,因为您按照的日期对匹配ID进行了分组。

如果您没有大量数据,可以在Ruby代码中完成所有操作:

Match.all.group_by { |match| match.matchDate.to_date }

这会为您提供一个哈希,其中日期为键,匹配列表为值。

此答案假定matchDate是时间,因为您在示例中使用了DATE(matchDate)。如果它已经是日期,则您不需要上面的.to_date位。

另请注意,SQL中的DATE(a_time_column)将提取数据库时区中的日期。 Rails通常将数据库配置为在内部使用UTC时区。因此,如果您确实使用这样的数据库查询,请注意这一点,并确保您获得正确的日期。

答案 1 :(得分:1)

问题是您要将matchId添加到group子句中。另一种选择是查找所有不同的日期并迭代它们以显示您的表格。我假设matchDate是一个Datetime,如果不是,它可能更干净。

distinct_dates = Match.pluck('DATE(matchDate)').uniq.compact
distinct_dates.each do |date|
  date = DateTime.parse(date_string)
  roles = Role.where( :created_at => (date)..(date + 1.day) )
  p date
  p roles.map(&:matchId)
end
相关问题