2012-04-22 91 views
0

列举我的博客文章时,我使用下单time_ago_in_words分组博客文章

time_ago_in_words(post.created_at) 

而不是每个列表中的time_ago_in_words在该帖子标题中列出,我想在一个标题下的不同职位的组,例如我可能有一个帖子“30分钟前”和8个帖子“一个月前” “

任何人都可以推荐最好的方法吗?

回答

2

您是否意识到time_ago_in_words是一种用Ruby语言编写的方法,因此您不能在您的sql-queries中使用它来执行数据库的分组和计算?

如果你有很多帖子,你必须制作一些sql-query来分组你的帖子。

但如果你告诉你的信息的量不是巨大的比你可以用简单的方法:

# in a controller 
@posts_map = Post.order('created_at DESC').all.group_by{|post| time_ago_in_words post.created_at } 

# in a view 
- @posts_map.each do |time, posts| 
    %h2 Created #{time} ago (#{posts.length}): 
    - posts.each do |post| 
    %h3= link_to post.title, post 
+0

感谢您的答复JDOE,但我想你已经错过,明白我的意思。我有一个博客首页,列出我所有的帖子,以及他们使用time_ago_in_words发布的时间。我想避免这种情况,我可能会连续发布3个帖子,标题都是“1个月前发布”。我想要的是在“1个月前”有一个标题,下面有三个帖子。 – pingu 2012-04-22 19:38:28

+1

这就是我的例子! '创建#{time}前(#{posts.length}):'显示标题和'posts.each do | post |'循环通过这个时间组。然后对另一个时间组也是如此。 – jdoe 2012-04-22 19:43:59

+0

我们可以考虑一个SQL选项还是没有真正的方法?我现在正在研究这个确切的事情。 – 2017-07-31 12:26:55