2010-12-12 17 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 2010-12-12 21:59:02

回答

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) 
相關問題