Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/53.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 将博客文章分组到单个时间\u-ago\u-in\u-words下_Ruby On Rails_Ruby_View - Fatal编程技术网

Ruby on rails 将博客文章分组到单个时间\u-ago\u-in\u-words下

Ruby on rails 将博客文章分组到单个时间\u-ago\u-in\u-words下,ruby-on-rails,ruby,view,Ruby On Rails,Ruby,View,我正在使用 time_ago_in_words(post.created_at) 当列出我的博客条目时 我希望在一个标题下有不同的帖子组,例如,我可能在“30分钟前”下有一篇帖子,在“一个月前”下有8篇帖子 有谁能推荐最好的方法吗?您是否意识到time\u ago\u in\u words是一种用Ruby语言编写的方法,因此您不能在sql查询中使用它来按DB执行分组和计数计算 如果你有很多文章,那么你必须手工制作一些sql查询来对你的文章进行分组 但是如果你说你的帖子数量并没有那么多,你可以使

我正在使用

time_ago_in_words(post.created_at)
当列出我的博客条目时

我希望在一个标题下有不同的帖子组,例如,我可能在“30分钟前”下有一篇帖子,在“一个月前”下有8篇帖子


有谁能推荐最好的方法吗?

您是否意识到
time\u ago\u in\u words
是一种用Ruby语言编写的方法,因此您不能在sql查询中使用它来按DB执行分组和计数计算

如果你有很多文章,那么你必须手工制作一些sql查询来对你的文章进行分组

但是如果你说你的帖子数量并没有那么多,你可以使用简单的方法:

# 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

谢谢你的回复,但我想你已经理解我了。我有一个博客首页,上面列出了我所有的帖子,以及它们使用time\u ago\u的文字发布的时间。我想避免的情况下,我可能有3个连续的职位都与相同的标题“张贴1个月前”。我想要的是有一个标题“1个月前”,下面有三篇文章。这正是我的例子所做的<代码>在{time}之前创建({posts.length}):显示标题和
posts。每个do | post{/code>循环通过此时间组。另一个时间组也是如此。我们能想出一个SQL选项吗?还是真的没有办法?我现在正在调查这件事。