Ruby on Rails:按月分组博客帖子 [英] Ruby on Rails: grouping blog posts by month

查看:122
本文介绍了Ruby on Rails:按月分组博客帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

小伙子。我创建了一个简单的博客应用程序与通常的CRUD操作。我还在PostController中添加了一个新的动作,名为archive和一个关联的视图。在这种观点下,我想把所有的博客帖子都带回来,并按月分组,以这种格式显示:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆