jay
jay

Reputation: 12495

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!

Upvotes: 4

Views: 1977

Answers (5)

webster
webster

Reputation: 4012

To get the last 10 records in descending order:

Post.last(10).reverse

Upvotes: -1

Christian Fazzini
Christian Fazzini

Reputation: 19723

In Rails 4, you can do

Post.order(created_at: :desc).limit(10)

Upvotes: 0

Faiq Adam
Faiq Adam

Reputation: 107

try this all

@recentposts = Post.order("created_at desc").limit(10)

Upvotes: 0

Ryan Bigg
Ryan Bigg

Reputation: 107728

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.

Upvotes: 12

jschorr
jschorr

Reputation: 3054

Try this:

@recentposts = Post.all(:order => 'created_at DESC', :limit => 10)

Upvotes: 7

Related Questions