Reputation: 12495
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
Reputation: 4012
To get the last 10 records in descending order:
Post.last(10).reverse
Upvotes: -1
Reputation: 19723
In Rails 4, you can do
Post.order(created_at: :desc).limit(10)
Upvotes: 0
Reputation: 107
try this all
@recentposts = Post.order("created_at desc").limit(10)
Upvotes: 0
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 inspect
ed that the SQL query actually runs.
Upvotes: 12
Reputation: 3054
Try this:
@recentposts = Post.all(:order => 'created_at DESC', :limit => 10)
Upvotes: 7