Rails ActiveRecord 按时间分组但用 nil 值填充日期?
因此,我使用 activerecord 来获取某一天的项目数:
Item.group("date(created_at)").count.values
但是如果某一天没有记录,这不会给我 0
,我该如何解决这个问题?或者有更多的“Rails”方式来做这样的事情吗?
非常感谢任何帮助,再次感谢!
So I'm using activerecord to get the count of items for a certain day:
Item.group("date(created_at)").count.values
But this doesn't give me 0
if there are no records for a given day, how can I fix this? Or is there are more "Rails" way do to something like this?
Any help is hugely appreciated, thanks again!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 GROUP BY 查询,您将根据现有记录获取组,因此,如果分组列中没有具有给定值的记录,则不会有该值的组。数据库在心理上不知道添加您可能感兴趣的其他日期值。
为了获得您想要的结果,我要做的是创建一个默认值为
0
的新哈希,然后合并您查询的结果。当您随后尝试从该哈希中检索没有条目的任何值时,您将得到 0 作为结果。编辑:删除
.values
或者,如果您想确保哈希中存在范围内每个日期的条目,以便您可以迭代这些条目,...
更新
这是当我将日期范围和模型传递到这里时的一些输出,奇怪的是它得到了不同长度的哈希值:
不确定是什么导致了它......嗯。
Using a GROUP BY query, you are going to get groups based on the records that exist, so if there are no records with a given value in the grouping column, there will be no groups for that value. The database does not psychically know to add in other date values that you might be interested in.
What I would do to get what you want is create a new Hash with a default value of
0
and then merge the result of your query into that. When you subsequently try to retrieve any value from that Hash for which there is no entry, you'll get 0 as the result.Edit: Remove
.values
Alternatively, if you want to make sure there are entries in the Hash for every date in a range, so you can iterate over those, ...
Update
Here is some output when I pass my date range and model into here, oddly enough it gets different length hashes:
Not sure whats causing it... hmm.