如何在ActiveRecord中将范围添加到SUM?

我想返回按当前季节的mountain_routes.hearts_count排序的用户。

我已经为此编写了一种方法,但是我的问题是该用户的所有mountain_routes的总和,而我只想按给定{{1} } 。

range

所以问题出在这部分def best_of_season range = start_date..end_date ::Db::User .joins(:mountain_routes) .where(mountain_routes: { route_type: 'regular_climbing',created_at: range }) .select('users.id,SUM(mountain_routes.hearts_count)') .group('users.id') .distinct .order('SUM(mountain_routes.hearts_count) DESC') end 中。 如何在给定的SUM(mountain_routes.hearts_count)中只放山路?

我想收到这样的输出:

range
kazmax 回答:如何在ActiveRecord中将范围添加到SUM?

您可以使用在SUM(mountain_routes.hearts_count)上添加别名并按order by子句使用它:

::Db::User
  .joins(:mountain_routes)
  .where(mountain_routes: { route_type: :regular_climbing,created_at: range })
  .select('users.id,SUM(mountain_routes.hearts_count) AS total_mountain_routes_hearts_count')
  .group(:id)
  .order('total_mountain_routes_hearts_count DESC')

由于您已经按users.id进行分组,因此必须首先摆脱这种独特的方法。

本文链接:https://www.f2er.com/3127939.html

大家都在问