Rails 将数据分组并渲染为 json

发布于 2024-10-12 05:14:25 字数 109 浏览 6 评论 0原文

我有一个带有许多优惠券的用户模型。每张优惠券都有其价值。

我想检索有关所有用户优惠券的一些数据,例如每个用户的所有优惠券价值的总和。我还想按天对数据进行分组。

我该怎么做?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

入画浅相思 2024-10-19 05:14:25

有一种称为 sum 的方法可以用于关联。例如:

@user.coupons.all.sum(&:value)

在本例中,值是您要求和的属性。

要按日期对它们进行分组,可能是这样的:

#group_by will create a hash with the dates as keys and place the coupons in arrays
@coupons = @user.coupons.all.group_by{ |coupon| coupon.created_at.strftime("%D") }

#Loop through all keys (dates) and get the sum of the coupons
@coupons.keys.each |date|
  puts "Date: #{date}, Value: #{@coupons[date].sum(&:value)}"
end

There is a method called sum that can be used on the associations. For example:

@user.coupons.all.sum(&:value)

In this case value is the attribute you want to sum.

And to group these by date, then perhaps something like this:

#group_by will create a hash with the dates as keys and place the coupons in arrays
@coupons = @user.coupons.all.group_by{ |coupon| coupon.created_at.strftime("%D") }

#Loop through all keys (dates) and get the sum of the coupons
@coupons.keys.each |date|
  puts "Date: #{date}, Value: #{@coupons[date].sum(&:value)}"
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文