Rails 将数据分组并渲染为 json
我有一个带有许多优惠券的用户模型。每张优惠券都有其价值。
我想检索有关所有用户优惠券的一些数据,例如每个用户的所有优惠券价值的总和。我还想按天对数据进行分组。
我该怎么做?
I have a User model with many coupons. Each coupon has a value.
I would like to retrieve some data about all the user coupons, like the sum of the value of all the coupons for each user. I also would like to group data by day.
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一种称为 sum 的方法可以用于关联。例如:
在本例中,值是您要求和的属性。
要按日期对它们进行分组,可能是这样的:
There is a method called sum that can be used on the associations. For example:
In this case value is the attribute you want to sum.
And to group these by date, then perhaps something like this: