Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Find the record with lowest value of a specific column

I am trying to find a record in the database that has the lowest value of its datetime column. In simpler words, I want to find a record with the earliest time.

I can use minimum to find the lowest value, but that will only return the value itself, and not the whole record.

I suppose I could create another query, but I'm wondering if there is a more efficient way of doing this.

like image 737
Goro Avatar asked Apr 11 '09 22:04

Goro


1 Answers

This will work:

earliest = Model.first(:order => 'column asc')

—Where Model is the name of your model class and column is the name of the datetime column. It will generate this SQL statement:

SELECT * FROM `Model` ORDER BY column asc LIMIT 1
like image 172
John Topley Avatar answered Oct 04 '22 03:10

John Topley