简体   繁体   English

在铁路中按月分隔日期

[英]Separating dates by month in rails

I understand in rails that you can query data using the controller which is what I have been doing. 我在rails中了解到你可以使用控制器来查询数据,这就是我一直在做的事情。

However say I have a list of dates and I want to visually display them under each month like so: 但是说我有一个日期列表,我想在每个月下直观地显示它们,如下所示:

August:
14/08/2015
25/08/2015
September:
12/09/2015
19/09/2015
October:
3/10/2015
8/10/2015
November:
25/11/2015
5/11/2015

Now I could query each month through the controller but in my eyes this is very inefficient. 现在我可以通过控制器查询每个月,但在我看来这是非常低效的。 As a result could you do something like this in the view? 结果你可以在视图中做这样的事情吗?

You can group the results with Ruby's collection group_by method : 您可以使用Ruby的集合group_by方法对结果进行分组:

@items_by_month = @items.group_by{|x| x.created_at.month}

It will result in a Hash with the following structure: 它将产生具有以下结构的哈希:

{
  # January
  1 => [item1, item2, ...],
  # February
  2 => [item3, item4, ...],
  # ... and so on
}

Then you can iterate over that Hash in your view. 然后,您可以在视图中迭代该哈希值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM