嘿伙计们。我使用常见的 CRUD 操作创建了一个简单的博客应用程序。我还在 PostController 中添加了一个名为“archive”的新操作和一个关联的视图。在此视图中,我想带回所有博客文章并按月对它们进行分组,以这种格式显示它们:
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 是一个很棒的方法:
控制器:
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
查看模板:
<% @posts_by_month.each do |monthname, posts| %>
<%= monthname %>
<ul>
<% posts.each do |post| %>
<li><%= post.title %></li>
<% end %>
</ul>
<% end %>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)