【发布时间】:2015-08-16 09:40:06
【问题描述】:
我有一组由 Active Record 查询返回的记录。我需要以某种方式迭代这些以构建一个看起来像这样的哈希数组:
[
{ '15/01/2013': 3 },
{ '24/051/2012': 1 },
{ '08/07/2015': 22 }
]
返回的记录形式为第一条记录 3 条,第二条记录 1 条,第三条记录 22 条。我基本上需要一种方法将其转换为像上面这样的简单哈希。
这是我的数据库输出示例:
[
{
"item_id": 21728,
"id": 31731,
"notes": "sample",
"date": "2014-09-12",
"created_at": "2015-08-13T15:16:06.074Z",
"updated_at": "2015-08-13T15:16:06.074Z"
},
{
"item_id": 21728,
"id": 31732,
"notes": "sample",
"date": "2014-09-12",
"created_at": "2015-08-13T15:16:06.104Z",
"updated_at": "2015-08-13T15:16:06.104Z"
},
{
"item_id": 21728,
"id": 31733,
"notes": "sample",
"date": "2014-09-13",
"created_at": "2015-08-13T15:16:06.112Z",
"updated_at": "2015-08-13T15:16:06.112Z"
}
]
【问题讨论】:
-
那么,也许你可以向我们展示一个查询和输出?
-
@Зелёный 好的,添加了我的数据库输出。谢谢
-
它是
json。在红宝石json != hash -
当您尝试迭代数据库结果时遇到了什么问题?
-
查看each_with_object - 它已在类似情况下使用过 - 您可以传递一个空哈希
{}作为初始值并在循环中 - 根据日期中的日期跟踪记录计数哈希
标签: ruby-on-rails ruby hash