2010-12-12 4 views
0

ブログエンジンにRailsを使用しています。投稿が公開された月と年のユニークなアーカイブ機能を実装しています。ブログアーカイブの別の日付を選択する

ここでキュウリの機能です:

Scenario: Displaying an archive menu from distinct posts months and years 
    Given the following posts exists for the blog "Blondinbella": 
     | Title   | Published at   | 
     | Redbull   | 1 March 2010 11:00 | 
     | Tuesday outfit | 2 January 2010 11:00 | 
     | Monday outfit | 1 January 2010 11:00 | 
     | Another outfit | 1 December 2009 11:00 | 
    When I visit the blog "Blondinbella" 
    Then I should see "March 2010" in the archive menu 
    And I should see "January 2010" in the archive menu 
    And I should see "December 2009" in the archive menu 
    But I should not see "February 2010" in the archive menu 

は、私は、このための最良のアプローチを考え出す苦労しています。私はSQLの質問でハードコアに行かなければならないとすれば、それはどのように見えるだろうか? (PostgreSQLの使用)

純粋なRailsを使用するだけで、これをスムーズに行う方法はありますか?

+1

SQLクエリを使用するには」だろうハードコア "? – araqnid

答えて

2

純粋なRubyの道:あなたはポストの多くを持っている場合、高負荷になります

Post.all.group_by { |post| post.published_at.strftime("%B %Y") }.map { |group| group.first.strftime("%B %Y") } 

。だから、SQLでそれを行うことができます:

Post.select("DISTINCT foo AS month").map(&:month) 

は日付をフォーマットするために何かしてfooを取り付けます(私は心でこれを行う方法を知らないので、自分でそれをルックアップする必要があります)

0

postgresqlでは、私はdate_truncメソッドを使うのが最も便利だとわかりました。

例:

Post.select("DISTINCT date_trunc('month', published_at) as month").collect(&:month) 

私はそれはまた、切り捨てを行う前に、あなたの地域のタイムゾーンに日付を変換するAT TIME ZONE構文を使用することは理にかなっていた:

Post.select("DISTINCT date_trunc('month', published_at AT TIME ZONE 'NZST') as month").collect(&:month) 
関連する問題