选择博客存档的不同日期

时间:2010-12-12 13:58:59

标签: ruby-on-rails postgresql cucumber

我正在使用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顺利完成这项工作?

2 个答案:

答案 0 :(得分: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替换为格式化日期的内容(我不知道如何做到这一点,所以你必须自己查看)

答案 1 :(得分: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)