gpt4 book ai didi

ruby-on-rails - Ruby on Rails : grouping blog posts by month

转载 作者:行者123 更新时间:2023-12-04 16:15:38 27 4
gpt4 key购买 nike

嘿伙计们。我已经使用通常的 CRUD 操作创建了一个简单的博客应用程序。我还在 PostController 中添加了一个名为“archive”的新操作和一个关联的 View 。在这个 View 中,我想带回所有博客文章并按月对它们进行分组,以这种格式显示它们:

March
<ul>
<li>Hello World</li>
<li>Blah blah</li>
<li>Nothing to see here</li>
<li>Test post...</li>
</ul>

Febuary
<ul>
<li>My hangover sucks</li>
... etc ...

我一生都无法找出最好的方法来做到这一点。假设 Post 模型具有通常的 title , content , created_at等领域,有人可以帮我解决逻辑/代码吗?我对 RoR 很陌生,所以请耐心等待:)

最佳答案

group_by 是一个很好的方法:

Controller :

def archive
#this will return a hash in which the month names are the keys,
#and the values are arrays of the posts belonging to such months
#something like:
#{ "February" => [#<Post 0xb5c836a0>,#<Post 0xb5443a0>],
# 'March' => [#<Post 0x43443a0>] }
@posts_by_month = Posts.find(:all).group_by { |post| post.created_at.strftime("%B") }
end

View 模板:
<% @posts_by_month.each do |monthname, posts| %>
<%= monthname %>
<ul>
<% posts.each do |post| %>
<li><%= post.title %></li>
<% end %>
</ul>
<% end %>

关于ruby-on-rails - Ruby on Rails : grouping blog posts by month,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1080547/

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