Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, how do I retrieve 10 most recent entries in a model?

Let's say I want to return the last entry in a model, it is easy. The most recent post is found as (assuming descending order)

 @post = Post.last 

What if I wanted the 10 most recent posts ie

 @recentposts = Post.#whatdoIputhere?

How could I most easily and efficiently do this?

Thanks!

like image 964
jay Avatar asked Dec 03 '22 01:12

jay


1 Answers

An an alternative to James Schorr's answer:

posts = Post.order('created_at DESC').limit(10)

The benefit of this alternative is that it allows you to continue to chain more relational scopes on the end of it:

posts.where(:user_id => 1)

It's not until the object is iterated over or inspected that the SQL query actually runs.

like image 73
Ryan Bigg Avatar answered Dec 04 '22 14:12

Ryan Bigg