我正在嘗試爲我的博客創建一個「存檔」頁面。它應列出所有博客標題,按照相反順序排列,按月排列。顯示博客文章的月度存檔
我使用的DataMapper沒有像MySQL這樣的DATE_FORMAT函數,這意味着我不能簡單地在查詢中進行分組。因此,我看到除了在普通的Ruby上做所有的努力之外別無他法。
這是我目前有:
# GOOD: order of posts within the months are correct
# BAD: order of months is random
@posts = Post.published(:order => :published_at.desc)
@months = {}
@posts.each do |post|
month_year = post.published_at.strftime("%B %Y")
@months[month_year] = [] unless @months.has_key? month_year
@months[month_year] << post
end
查看:
.archive
- @months.each do |month, posts|
%h2= month
%ol
- posts.each do |post|
= partial(post)
此我想要做什麼,除了幾個月的順序弄亂了,因爲它們包含的散列內。 (我在Ruby 1.8中,所以散列的順序實際上是隨機的)。
如何使月份的順序正確?我可能需要使用數組,但我無法弄清楚其他代碼的外觀。
謝謝,成功了! – Marc 2011-04-04 23:31:42