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

Bar*_*her 5 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 ...
Run Code Online (Sandbox Code Playgroud)

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

Max*_*man 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
Run Code Online (Sandbox Code Playgroud)

查看模板:

<% @posts_by_month.each do |monthname, posts| %>
<%= monthname %>
<ul>
   <% posts.each do |post| %>
     <li><%= post.title %></li>
   <% end %>
</ul>
<% end %>
Run Code Online (Sandbox Code Playgroud)

  • 这与OP更相关:*您可能希望按年份分组,因为一旦它转到下一年(例如,2010年),那么1月份的部分将包含2009年和2010年的条目.*您可能希望每个月的条目按(日)日期排序,以确保列表按时间顺序排列. (3认同)
  • 完美解决方案 非常感谢 :) (2认同)

Ste*_*ers 7

@Maximiliano Guzman

好答案!感谢您为Rails社区增加价值.我将原始资料包含在如何使用Rails创建博客存档中,以防万一我对作者的推理进行了抨击.根据博客文章,对于Rails的新开发人员,我会添加一些建议.

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

最后,按照相同的方式,使用ActiveRecord核心扩展中的beginning_of_month方法.我觉得beginning_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
Run Code Online (Sandbox Code Playgroud)

意见/档案馆/ 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>
Run Code Online (Sandbox Code Playgroud)

祝你好运,欢迎来到Rails!