假设我想返回模型中的最后一个条目,这很容易。最近的帖子被发现为(假设降序)
@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/