0
votes

I am learning rails and stuck on a problem. it resembles Ryan Bates http://railscasts.com/episodes/29-group-by-month problem but it is failing.

My setup is the following:

class EventsController < ApplicationController
def index
    @events = Event.all
    @events_by_month = @events.group_by { |x| [x.date.beginning_of_month] }

end

Case 1:

<% @events_by_month.keys.sort.each do |month| %>
    <% for firm in @events_by_month[month] %>
       <%= firm.name %>  <%= firm.date.to_date.to_s(:long) %>
    <% end %><br>
<% end %>

This gives me results of:

Little LLC October 24, 2014
Kovacek, Borer and Dickinson October 16, 2014
Rogahn-Cruickshank October 6, 2014
Harris-Dicki October 31, 2014

Kutch-Schulist November 18, 2014

Dicki, Gleason and Cremin December 7, 2014
Robel, Simonis and Bechtelar December 28, 2014
Kuvalis-Schumm December 23, 2014

Case 2: If I insert month.strftime then I get an error.

<% @events_by_month.keys.sort.each do |month| %>
    <h2><%= month.strftime("%B %Y") %></h2>
    <% for firm in @events_by_month[month] %>
       <p> <%= firm.name %>  <%= firm.date.to_date.to_s(:long) %></P>
    <% end %><br>
<% end %>

Case 1- Problem: The results are grouped by month but not in order. According to the tutorial it should have ordered the hash.

Case 2 - Problem: I get an error of : undefined method `strftime' for [Mon, 01 Sep 2014 00:00:00 UTC +00:00]: Extracted source (around line #2):

I have looked at Ruby on Rails group_by (how to group events by month) and it did print the month but hash was still out of order.

Summary: I am looking for help on ordering the items within the grouped month and also displaying the month. I am using Ruby ruby 2.1.4p265 (2014-10-27 revision 48166) [x86_64-darwin14.0] and Rails 4.2. Thank you in advance

2

2 Answers

1
votes

I believe you forgot to sort events in the query itself

class EventsController < ApplicationController
def index
    @events = Event.all.order(:date)
    # HERE: You don't need to enclose that in array, that's why it fails in view
    @events_by_month = @events.group_by { |x| x.date.beginning_of_month }

end

Then in view you can do

<% @events_by_month.each do |begin_month, events| %>
    <h2><%= begin_month.strftime("%B %Y") %></h2>
    <% events.each do |firm| %>
       <p> <%= firm.name %>  <%= firm.date.to_date.to_s(:long) %></P>
    <% end %><br>
<% end %>

No need to sort in view now, it's already sorted (and database it's much more performant in doing this)

0
votes

how about this code in your views.

     <% @events_by_month.sort.each do |month, value| %>
        #note both month and value are array
        <h2><%= month.first.strftime("%B %Y") %></h2>
        <% events.sort_by!{|g| g.date.beginning_of_month}.each do |firm| %>
          #print things against firm
        <% end %>
     <% end %>