2011-03-27 8 views
1

私は自分のブログのために「アーカイブ」ページを作成しようとしています。それは月ごとにグループ化された逆の順序で慢性的に順序付けられたすべてのブログタイトルを一覧表示する必要があります。ブログ記事の月間アーカイブを表示する

私は、MySQLのようなDATE_FORMAT機能を持たないDataMapperを使用しています。これは単にクエリ内でグループ化することができないことを意味します。そのために私は、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

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

関連する問題