为博客存档选择不同的日期
我正在使用 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 顺利地完成此操作?
I'm using Rails for a blog engine. I'm implementing an archive feature that archives based on unique month and years where a post has been published.
Here's the cucumber feature:
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
I am having a hard time figuring out the best approach for this. Should I go hardcore with a SQL-query and if so how would that look? (Using PostgreSQL)
Or is there a way of doing this smoothly just using pure Rails?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
纯 Ruby 方式:
如果您有很多帖子,这将是一个沉重的负担。所以你可以在 SQL 中做到这一点:
将
foo
替换为格式化日期的内容(我不知道如何用心做到这一点,所以你必须自己查找)The pure Ruby way:
Which will be a heavy load if you have a lot of posts. So you could do it in SQL:
Replace the
foo
with something to format the date (I don't know how to do this by heart, so you'll have to look that up yourself)对于 postgresql,我发现使用 date_trunc 方法最有用。
例如:
我发现在进行截断之前使用 AT TIME ZONE 构造将日期转换为本地时区也是有意义的:
With postgresql, I found using the
date_trunc
method the most useful.eg:
I found it also makes sense to use the
AT TIME ZONE
construct to convert the date to your local timezone before doing the truncation: