This returns the maxium value, not the complete record:
self.prices.maximum(:price_field)
And currently, I find the record like this:
def maximum_price
self.prices.find(:first, :conditions => "price = #{self.prices.maximum(:price_field)}" )
end
Is this the correct way ? Because the above needs two SQL statements to make it work, and it somehow does not feel right.
Ps. Additionally, I want that if more than one record has the same "maximum" value, then it should get the one with the latest updated_at
value. So that would mean another SQL statement??
Pps. Does anyone know of a good or detailed reference for AREL and non-AREL things in Rails? The Rails Guide for ActiveRecord query is just not enough!
(I'm using Rails 3)
Using AREL I do the following:
self.prices.order("updated_at DESC").maximum(:price_field)
But this only gives the maximum value, not the complete record :(
Also, is the use of maximum()
really AREL?
Select row with max date per user using MAX() function Another way to get the latest record per user is using inner queries and Max() function. Max() function, when applied on a column, gives the maximum value of that column.
MySQL MAX() function with GROUP BY retrieves maximum value of an expression which has undergone a grouping operation (usually based upon one column or a list of comma-separated columns).
To find the maximum value of a column, use the MAX() aggregate function; it takes a column name or an expression to find the maximum value. In our example, the subquery returns the highest number in the column grade (subquery: SELECT MAX(grade) FROM student ).
How about something like this?
self.prices.order("price DESC").first
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With