【问题标题】:Loop variable grouping by date循环变量按日期分组
【发布时间】:2017-02-14 18:12:52
【问题描述】:

我有一些体育赛事的结果,我想在表格中循环查看并根据日期分组。例如;

|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|

【问题讨论】:

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


    【解决方案1】:

    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 时区。因此,如果您确实使用这样的数据库查询,请注意这一点并确保您获得正确的日期。

    【讨论】:

    • 谢谢亨利克。我确实有很多跨协会的数据。
    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-07
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多