显示选定数量的博客条目

发布于 2024-12-19 09:20:24 字数 205 浏览 1 评论 0原文

我对使用 Ruby on Rails 还很陌生。 我创建了一个名为“posts”的博客,我希望我的主页显示 2 个最新条目...

到目前为止,我已经显示了所有使用的博客文章

<% @posts.each do |post| %>

,但如何修改它以仅显示最新的 2 个条目?

非常感谢。

I'm fairly new to working with Ruby on Rails.
I've created a blog called "posts", and I want my homepage to display the 2 latest entries...

I've so far got it displaying ALL blog posts using

<% @posts.each do |post| %>

but how do I modify this to show only the latest 2?

Many thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怎会甘心 2024-12-26 09:20:24
@posts = Post.order('created_at desc').limit(2)
@posts = Post.order('created_at desc').limit(2)
ぽ尐不点ル 2024-12-26 09:20:24

假设您的控制器中有类似 @posts = Post.all 的内容,您只需执行以下操作:

@posts = Post.last(2)

Assuming you're having something like @posts = Post.all in your controller, you'd just do the following instead:

@posts = Post.last(2)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文