How to find the record with the maximum price?

Zabba picture Zabba · Jan 27, 2011 · Viewed 16.1k times · Source

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)

===UPDATE===

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?

Answer

TK-421 picture TK-421 · Jan 27, 2011

How about something like this?

self.prices.order("price DESC").first