Ruby on Rails:按月分组博客帖子 [英] Ruby on Rails: grouping blog posts by month
问题描述
March
< ul>
< li> Hello World< / li>
< li> Blah blah< / li>
< li>无法看到这里< / li>
< li>测试帖子...< / li>
< / ul>
Febuary
< ul>
< li>我的宿醉吸吮< / li>
...等...
我不能为我的生活出最好的方法来做到这一点。假设Post模型具有通常的标题
,内容
, created_at
等字段,有人可以帮我出来的逻辑/代码?我很喜欢RoR,所以请与我保持联系:)
group_by是一个很好的方法:
控制器:
def archive
#this将返回一个哈希,其中月份名称是键
#,值为属于这些月份的帖子的数组
#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
查看模板: / p>
<%@ posts_by_month.each do | monthname,posts | %GT;
<%= monthname%>
< ul>
<%posts.each do | post | %GT;
< li><%= post.title%>< / li>
<%end%>
< / ul>
<%end%>
Hy guys. I've created a simple blog app with the usual CRUD actions. I've also added a new action in the PostController called "archive" and an associated view. In this view I want to bring back all blog posts and group them by month, displaying them in this kind of format:
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 ...
I can't for the life of me figure out the best way to do this. Assuming the Post model has the usual title
, content
, created_at
etc fields, can someone help me out with the logic/code? I'm very new to RoR so please bear with me :)
group_by is a great method:
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 template:
<% @posts_by_month.each do |monthname, posts| %>
<%= monthname %>
<ul>
<% posts.each do |post| %>
<li><%= post.title %></li>
<% end %>
</ul>
<% end %>
这篇关于Ruby on Rails:按月分组博客帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!