The MurifoX clause does not work because LIMIT applies only to the final result set, which has only one row (sum). See this thread .
The easiest way to solve this is not to do an account in the database:
Model.where(:id => id).order('date DESC').limit(3).pluck(:column).compact.sum
Loads column values โโinto Ruby and sums them there. Now, if the record set is really huge, it will be noticeably less efficient, just because all of these values โโare loaded into your application memory.
Edit: Added .compact - this will remove nils from the array before adding it (which causes an error).
The suggested method for doing this in SQL uses a subquery, for example:
SELECT SUM(subquery.column) FROM ( SELECT * FROM models WHERE id = 5 LIMIT 3 ) AS subquery;
There is really no simple or easy way to turn this into an ActiveRecord query, as they are awaiting selection from a particular model table.
source share