In Rails, how do I get the last 10 entries in a model?

Let's say I want to return the last entry in the model, it's easy. Latest publication found as (in decreasing order)

@post = Post.last 

What if I need the last 10 posts, i.e.

  @recentposts = Post.#whatdoIputhere? 

How can I do this most easily and efficiently?

Thanks!

+4
source share
5 answers

Try the following:

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

Alternative to James Shorr:

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

The advantage of this alternative is that it allows you to continue linking more relational areas at the end:

 posts.where(:user_id => 1) 

This is not until the object is renamed or inspect ed, which actually executes the SQL query.

+12
source

try it all

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

0
source

In Rails 4 you can do

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

To get the last 10 entries in descending order:

 Post.last(10).reverse 
0
source

All Articles