【问题标题】:Rails group records by dates of created_at retrieve hash with date string as the keyRails 按 created_at 的日期对记录进行分组,以日期字符串为键检索哈希
【发布时间】:2020-12-20 18:02:31
【问题描述】:

我正在尝试从模型中检索记录并按日期对它们进行分组通过created_at 字段。

我的问题是我不确定如何获取以日期字符串为键的哈希。 我正在做Model.group('date(created_at)').count,它返回{Sat, 19 Dec 2020=>9, Sun, 20 Dec 2020=>7}

我想要的是{'2020-12-19'=>9, '2020-12-20'=>7}

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    您应该将日期转换为 string,否则 rails 将格式化日期。

    Model.group("to_char(date(created_at), 'yyyy-mm-dd')").count
    

    这应该给出你需要的输出哈希

    【讨论】:

      猜你喜欢
      • 2014-04-01
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 2015-03-25
      • 1970-01-01
      相关资源
      最近更新 更多