Separation by month in rails

I understand in rails that you can query data using a controller, which is what I do.

However, I will say that I have a list of dates and I want to visually display them each month like this:

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 can query every month through the controller, but in my eyes it is very inefficient. As a result, could you do something like this in the view?

+3


source to share


1 answer


You can group the results using the Ruby collection method group_by :

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

      

This 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 this hash in your view.

0


source







All Articles