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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With