Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord "maximum(:column)" ignores order

I am trying to retrieve the maximum value of a column using ActiveRecord, but after I order and limit the values.

My query is:

max_value = current_user.books.order('created_at DESC').limit(365).maximum(:price)

Yet the resulting query is:

(243.0ms)  SELECT MAX(`books`.`price`) AS max_id FROM `books` WHERE `books`.`user_id` = 2 LIMIT 365

The order is ignored completely and as a result the maximum value comes from the first 365 records instead of the last 365 records.

like image 957
Georgios UK Avatar asked Apr 30 '26 00:04

Georgios UK


1 Answers

There's a curious line in the active record code (active_record/relation/calculations.rb) which removes the ordering. I say curious because it refers specifically to postgres:

# Postgresql doesn't like ORDER BY when there are no GROUP BY
relation = reorder(nil)

You should be able to use pluck to achieve what you want. It can select a single attribute which can be a reference to an aggregate function:

q = current_user.books.order('created_at DESC').limit(365)
max_value = q.pluck("max(price)").first

pluck will return an array of values so you need the first to get the first one (and only one in this case). If there are no results then it will return nil.

like image 191
Shadwell Avatar answered May 01 '26 13:05

Shadwell