2011-03-27 94 views
1

我正在嘗試爲我的博客創建一個「存檔」頁面。它應列出所有博客標題,按照相反順序排列,按月排列。顯示博客文章的月度存檔

我使用的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中,所以散列的順序實際上是隨機的)。

如何使月份的順序正確?我可能需要使用數組,但我無法弄清楚其他代碼的外觀。

回答

1
# Creating random data to similate your DataMapper array 
require 'date' 
require 'ostruct' 

posts = 10.times.inject([]) {|s,i| s << OpenStruct.new(:id => i, :published_at => Date.parse("2010-#{rand(11)+1}-#{rand(25)+1}"), :title => "title #{i}")} 

# Your code starts here 
ordered_posts = posts.inject({}) do |s,p| 
    ym = p.published_at.strftime('%Y-%m') 
    s.merge(s[ym] ? {ym=>s[ym]<<p} : {ym=>[p]}) 
end.sort {|a,b| b[0] <=> a[0]} 

# then in your view do 
ordered_posts.each do |op| 
    puts op[0][-2,2] # your %h2 line 
    op[1].sort {|a,b| b.published_at <=> a.published_at}.each do |p| 
    puts " #{p.published_at.strftime('%m/%d/%y')}-#{p.title}" # your partial(posts) line 
    end 
end 

生產:

[email protected]:~/code_katas> ruby blogs.rb 
11 
    11/10/10-title 9 
10 
    10/21/10-title 2 
09 
    09/17/10-title 8 
08 
    08/21/10-title 1 
    08/06/10-title 3 
07 
    07/06/10-title 6 
06 
    06/07/10-title 5 
05 
    05/12/10-title 7 
03 
    03/16/10-title 4 
01 
    01/17/10-title 0 
+0

謝謝,成功了! – Marc 2011-04-04 23:31:42

0
# posts_controller 
@months = @posts.group_by { |post| post.published_at.strftime("%B %Y")} 

# archive view 
.archive 
    - @months.each do |month, posts| 
    %h2= month 
    %ol 
     = render posts 
+0

我試過了你的代碼,但由於某些原因,月份仍然以看似隨機的順序,就好像group_by沒有任何效果一樣。 – Marc 2011-04-04 23:32:32