Ruby on Rails:按月分组博客文章

时间:2009-07-03 19:24:06

标签: ruby-on-rails crud

嗨伙计们。我用通常的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模型有通常的titlecontentcreated_at等字段,有人可以帮我解决逻辑/代码吗?我对RoR很新,所以请耐心等待我:)

2 个答案:

答案 0 :(得分:31)

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 %>

答案 1 :(得分:7)

@Maximiliano Guzman

很好的答案!感谢您为Rails社区增加价值。我将原始资料包括在How to Create a Blog Archive with Rails,以防万一我对作者的推理进行了抨击。根据博客文章,对于Rails的新开发人员,我会添加一些建议。

首先,使用Active Records Posts.all 方法返回Post结果集,以提高速度和互操作性。已知 Posts.find(:all)方法存在无法预料的问题。

最后,同样,使用ActiveRecord核心扩展中的 beginning_of_month 方法。我发现 starts_of_month strftime(“%B”)更具可读性。当然,选择权归你所有。

以下是这些建议的示例。有关更多详细信息,请参阅原始博文:

控制器/ archives_controller.rb

def index
    @posts = Post.all(:select => "title, id, posted_at", :order => "posted_at DESC")
    @post_months = @posts.group_by { |t| t.posted_at.beginning_of_month }
end

视图/档案/ indext.html.erb

<div class="archives">
    <h2>Blog Archive</h2>

    <% @post_months.sort.reverse.each do |month, posts| %>
    <h3><%=h month.strftime("%B %Y") %></h3>
    <ul>
        <% for post in posts %>
        <li><%=h link_to post.title, post_path(post) %></li>
        <% end %>
    </ul>
    <% end %>
</div>

祝你好运,欢迎来到Rails!