Well last(5)
(or more generally last(n)
) is a method defined on Array
, which means the ActiveRecord::Relation
you've build by calling Player.joins(:game).order('games.scheduled_start ASC')
will be evaluated to an array and then last(5)
will be called on that resulting array.
Rails adds the ability to call sum
on an array, but it will work differently than on an ActiveRecord::Relation
(by calling +
on each object and the current sum, starting with 0
).
Instead you will probably want to use this:
players = Player.joins(:game).order('games.scheduled_start DESC').limit(5)
sum = Player.joins(:game).where(id: players).sum(:ppg)
Note that i've switched from ASC
to DESC
, as limit will always take elements from the beginning. Now sum
will actually be translated to the corresponding SQL aggregate function, which will work on the :ppg
-column.
The where
-clause is needed in order to trigger a subquery, to ensure that sum
will
only work on those players selected by limit
.
If you however actually want to work with an Array (which will be slower), you can use this method:
players = Player.joins(:game).order('games.scheduled_start ASC').last(5)
# builds the sum of all ppg-values of all players selected
sum = players.sum(&:ppg)
But average
will only work on an ActiveRecord::Relation
, as it is not defined on
Array
(not even in Rails). You can, of course, build it yourself, but again, the
ActiveRecord::Relation
method will be faster.