Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails - activerecord ... grab first result

I want to grab the most recent entry from a table. If I was just using sql, you could do

Select top 1 * from table ORDER BY EntryDate DESC

I'd like to know if there is a good active record way of doing this.
I could do something like:

table.find(:order => 'EntryDate DESC').first

But it seems like that would grab the entire result set, and then use ruby to select the first result. I'd like ActiveRecord to create sql that only brings across one result.

like image 368
Daniel Avatar asked Dec 29 '22 16:12

Daniel


1 Answers

You need something like:

Model.first(:order => 'EntryDate DESC')

which is shorthand for

Model.find(:first, :order => 'EntryDate DESC')

Take a look at the documentation for first and find for details.

like image 130
Stephen Veiss Avatar answered Jan 13 '23 22:01

Stephen Veiss