2013-05-06 80 views
1

我一直在與代碼戰鬥了一段時間,現在我真的無法從中得到任何好處!通過幾年和幾個月循環Ruby On Rails

我正在創建一個博客檔案,我正在尋找一種方法從created_at中獲得所有年份和月份。可以說,我得到了2011,2012和2013年的許多帖子。

下面的這個「代碼」僅僅是我想要構建的結構的一個例子(這只是讓你瞭解我希望它看起來像)

years.each do |y| 
    puts y.created_at.year 

     y.created_at.month.each do |m| 
     puts m.created_at.month 

      (And ye, posts for each months loops here) 

     end 

end 

我以後的輸出是一樣的東西:

2013 
    May 
    Name of post 
    Name of post 
    April 
    Name of post 
    Name of post 
    Mars 
    Name of post 
    Name of post 

2012 
    December 
    Name of post 
    Name of post 
    November 
    Name of post 
    Name of post 
    October 
    Name of post 
    Name of post 

我希望我做得很清楚!我相信這比我現在想的要簡單得多!真的很感謝這裏的一些幫助!

回答

1
month, year = nil, nil 
Post.order("created_at desc") do |post| 
    if year != post.created_at.year 
    year = post.created_at.year 
    puts year 
    end 

    if month != post.created_at.month 
    month = post.created_at.month 
    puts "\t#{post.created_at.strftime("%B")}" 
    end 

    puts "\t\t#{post.name}" 
end 
+0

隨着一些細微的修改,像一個魅力工作!簡單而好,就像我想要的一樣。想到所有帖子的循環內部if語句從來沒有記住我的想法......非常感謝您的快速和良好的awnser! – 2013-05-06 22:12:44