Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the newest record in Rails 3

I was wondering if there is a way to find the newest record in a table in rails3?

like image 428
Elliot Avatar asked Feb 02 '11 03:02

Elliot


2 Answers

Given a Post model, you could do @post = Post.order("created_at").last

(The reason I didn't just do a @post = Post.last is because that always defaults to sort by your primary key (usually id). Most of the time this is fine, but I'm sure there's a scenario where that could cause problems (e.g. setting custom IDs on records, database changes which affect the primary key sequencing/autonumbering, etc.). Sorting by the created_at timestamp ensures you are really getting the most recent record).

like image 171
Dylan Markow Avatar answered Sep 23 '22 12:09

Dylan Markow


While dmarkow's answer is technically correct, you'll need to make an index on created_at or risk an increasingly slow query as your database grows.

If you know that your "id" column is an auto-increment primary key (which it likely is), then just use it since it is an index by definition.

Also, unless AREL is optimized to select only one record in a find(:last), you run the risk of making it select ALL records, then return you just the last one by using the "last()" method. More efficient is to limit the results to one:

MyModel.last(:order => "id asc", :limit => 1) 

or

MyModel.first(:order => "id desc", :limit => 1) 
like image 37
jemminger Avatar answered Sep 22 '22 12:09

jemminger