2009-07-03 73 views
5

Hy guys。我使用通常的CRUD操作創建了一個簡單的博客應用程序。我還在PostController中添加了一個名爲「歸檔」和相關視圖的新動作。在這種觀點我想一個月帶回的所有博客文章,並將它們組合,在這種格式來顯示他們:Ruby on Rails:按月分組博客文章

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

我不能爲我的生活想出解決問題的最好的辦法。假設郵政模型有通常的title,content,created_at等字段,有人可以幫助我與邏輯/代碼?我很新的回報率,所以請多多包涵:)

回答

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

這與OP更相關:*您可能希望按年份分組,因爲一旦它轉到下一年(比如2010),那麼1月份的部分將包含2009年和2010年的條目。 *您可能希望每個月的條目按(日期)排序,以確保列表按時間順序排列。 – BryanH 2009-07-03 19:56:41

+2

完美的解決方案!非常感謝:) – 2009-07-03 20:18:17

7

@Maximiliano古斯曼

很好的答案!感謝您爲Rails社區增加價值。我在How to Create a Blog Archive with Rails上加入了我的原始資料,以防我作者的推理。根據博客文章,對於Rails的新開發人員,我會添加一些建議。

首先,使用Active Records Posts.all方法返回Post結果集以提高速度和互操作性。已知方法Posts.find(:all)有無法預料的問題。

最後,沿着同樣的脈絡,從ActiveRecord核心擴展中使用beginning_of_month方法。我發現beginning_of_monthstrftime(「%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!