[英]In Rails, how do I retrieve 10 most recent entries in a model?
假設我想返回模型中的最后一個條目,這很容易。 發現最近的帖子(假設降序排列)
@post = Post.last
如果我想要10個最近的帖子,即如果
@recentposts = Post.#whatdoIputhere?
我怎樣才能最輕松有效地做到這一點?
謝謝!
詹姆斯·肖爾的答案的另一種選擇:
posts = Post.order('created_at DESC').limit(10)
這種替代方案的好處是它允許您在最后繼續鏈接更多的關系范圍:
posts.where(:user_id => 1)
直到對象被迭代或inspect
到SQL查詢實際運行。
嘗試這個:
@recentposts = Post.all(:order => 'created_at DESC', :limit => 10)
試試這一切
@recentposts = Post.order(“created_at desc”)。limit(10)
在Rails 4中,你可以做到
Post.order(created_at: :desc).limit(10)
要按降序獲取最后10條記錄:
Post.last(10).reverse
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.