gpt4 book ai didi

ruby-on-rails - 在 Rails 中,如何检索模型中的 10 个最新条目?

转载 作者:行者123 更新时间:2023-12-03 18:23:52 25 4
gpt4 key购买 nike

假设我想返回模型中的最后一个条目,这很容易。最近的帖子被发现为(假设降序)

 @post = Post.last 

如果我想要 10 个最近的帖子怎么办,即
 @recentposts = Post.#whatdoIputhere?

我怎样才能最轻松有效地做到这一点?

谢谢!

最佳答案

James Schorr 答案的替代方法:

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

这种替代方案的好处是它允许您继续在其末尾链接更多关系范围:
posts.where(:user_id => 1)

直到对象被迭代或 inspect ed SQL 查询实际运行。

关于ruby-on-rails - 在 Rails 中,如何检索模型中的 10 个最新条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7475639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com